Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery select all elements with an innerHTML that starts with a string?

I know you can use :contains to get elements who's innerHTML contains a certain string, but how can I get the elements whose innerHTML starts with a string?

like image 854
DevDevDev Avatar asked Sep 02 '10 20:09

DevDevDev


People also ask

Does innerHTML return a string?

Reading the HTML contents of an element Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the element's descendants. The resulting string is returned.

Why you shouldn't use innerHTML?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies. You can read the MDN documentation on innerHTML .

Can you += innerHTML?

Appending to innerHTML is not supported: Usually, += is used for appending in JavaScript. But on appending to an Html tag using innerHTML, the whole tag is re-parsed.

How do I get innerHTML text?

Setting the innerHTML property of an element To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.


3 Answers

Using a filter function you can filter based on any criteria that you'd like:

var spans = $("span").filter(function(idx) {
   return this.innerHTML.indexOf(myString) == 0;
});
like image 112
joshperry Avatar answered Sep 28 '22 08:09

joshperry


I know this is old, but if anyone is looking for a better answer, jQuery since v1.1.4 has a ":contains("text")" selector.

Example HTML:

<p>Please reply above this line...</p>

Example jQuery selects above HTML:

$('p:contains("Please reply above this line")');
like image 25
yincrash Avatar answered Sep 28 '22 09:09

yincrash


You could do something like this:

<!doctype HTML>
<html>
<head>
<script type = "text/javascript" language = "JavaScript" src = "jquery-1.4.2.min.js"></script>
<script type = "text/javascript" language = "JavaScript">
var elems;
$(document).ready(function(){
    $("div").each(function(){
        var content = $(this).html();
        if (content.match(/asdf/)){
            alert(content);
        }
    });
});
</script>
</head>
<body>
<div>asdfaowhguiwehgiuh</div>
<div>asdfaowhguiwehgiuh</div>
<div>fdsaaowhguiwehgiuh</div>
<div>fdsaaowhguiwehgiuh</div>
<div>fdsaaowhguiwehgiuh</div>
<div>asdfaowhguiwehgiuh</div>
</body>
</html>

In order to find whether it's in the content at all..if you want the first few characters you should split the content on those characters and test just it.

like image 38
KeatsKelleher Avatar answered Sep 28 '22 08:09

KeatsKelleher