I have the following html:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<span>not so important</span>
<span title="some specific text"><img src="/img/some.gif" /></span>
<span title="more specific text">important 1</span>
<span title="more specific text">important 2</span>
<span title="more specific text">important 3</span>
<span title="more specific text"><img src="/img/some.gif" /></span>
<ul>
<li>example 1</li>
<li>example 2</li>
<li>example 3</li>
<ul>
<script>
var ul = $('body').append($('<ul>'));
$("span[title*='specific text']")
.contents()
.filter(function(){ return $(this).nodeType != 1; })
.each(function(){
ul.append($('<li>' + $(this).text() + '</li>'));
})
</script>
</body>
</html>
I want to retrieve the text within a ‘span’ whose title attribute contains “specific text”, in this case “important 1”, “important 2” and “important 3”. Then I want to list them below just like the example. However the bullets do not appear, why is that? Any hints would be appreciated!
EDIT: http://jsfiddle.net/XTqjC/3/ this is the code that does what I need it to do. Thanks to Glen and meo
In your example you haven’t closed your
<ul>properly (missing the slash). Is that a copy+paste error, or in your code as well?Edit: And
you needit is good practice to have a semi-colon after your each() (see comments):Try the following:
Of course, the
$(this).text()won’t allow you to place the<img>in the<li>s. So you’ll end up with an empty<li></li>for each. This could be fixed with the following: