Reputation: 79
My task is to output the contents of my div Id's in a formatted rectangle. I have everything working correctly for my 'p' elements but can't seem to figure out how to get the 'span' elements. I know it should be easy but I've run out of ideas (maybe because it's 3am). The code below is working for me, but I can't figure out where to add the 'span'.
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<h1 >DOM Example</h1>
<div id="weekday"> weekdays
<p>Monday</p>
<p>Tuesday</p>
<p>Wednesday</p>
<p>Thursday</p>
<p>Friday</p>
</div>
<div id="weekend"> weekends
<p>Saturday</p>
<p>Sunday</p>
</div>
<div id="summer"> summer
<span> June</span>
<span> July</span>
<span> August</span>
</div>
<p>Thank you</p>
<p>Have a nice day</p>
<div id="rectangleDiv">
</div>
<script>
var input = prompt("Input weekend, weekday, or summer");
var matches = [];
var searchEles = document.getElementById(input).children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'p' || searchEles[i].tagName == 'P') {
matches.push(searchEles[i].innerText);
}
}
var rectangle = document.getElementById("rectangleDiv");
rectangle.setAttribute("style","width:250px;height:200px;background-color:cyan;color:blue;border-color:red;border-size:3px;border-style:solid;");
var i;
for(i=0;i<matches.length;i++) {
rectangle.innerHTML +=matches[i]+"<br>";
}
</script>
</body>
</html>
Upvotes: 1
Views: 105
Reputation: 7026
You need to use .querySelectorAll('p, span')
like so:
var input = document.getElementById(prompt("Input weekend, weekday, or summer"));
var spans = input.querySelectorAll('p, span');
for(var i = 0, l = spans.length; i < l; i++){
console.log(spans[i].textContent || spans[i].innerText);
}
Upvotes: 0
Reputation: 557
Universal solution is to find elements by class
if(searchEles[i].className == 'elementToFind')
and then process result as needed. It will find all the results at once for summer will be: "June July August"
<div id="summer"> summer
<strong class="elementToFind"> June</span>
<h2 class="elementToFind"> July</span>
<span class="elementToFind"> August</span>
</div>
Upvotes: 0
Reputation: 532
You can do this in the same way you got the text from the "p" elements, add a check on "span".
jsfiddle code: http://jsfiddle.net/fxatn8kv/
if(searchEles[i].tagName == 'p' || searchEles[i].tagName == 'P' || searchEles[i].tagName.toLowerCase() == 'span')
Upvotes: 0
Reputation: 193261
Just check for span
tag name too, since you can have either p
or span
as children:
if (searchEles[i].tagName == 'P' || searchEles[i].tagName == 'SPAN') {
matches.push(searchEles[i].innerText);
}
By the way, Element.tagName
is always uppercase string, so no need to check for lower p
and span
.
Demo: http://jsfiddle.net/ax5pn09L/
Upvotes: 2
Reputation: 1578
Try using
document.getElementsByTagName('span
)`
Or
querySelectorAll('span')
But be aware that you wont get a string as return
Upvotes: 0