How do I find all h3
on a page that include an ID attr
, save them into an array, then output them somewhere else as a list (with the H3 as the value, and the id as a href)? Preferably with jQuery, or possible PHP if not.
This is what I've come up with so far to create the arrays (I'd prefer them in a single array):
var ids = [];
var values = [];
i = 0;
e = 0;
$('h3').each(function()
{
if($(this).attr('id')){
ids[i ] = $(this).attr('id');
values[e ] = $(this).text();
}
});
So if we then had HTML like this:
<div class="headers">
<h3 id="first">First</h3>
<h3 id="second">Second</h3>
<h3>None</h3>
<h3 id="third">Third</h3>
<h3>None Do not Show</h3>
</div>
<div class="headers-in-here"></div>
I would want the output in "headers-in-here" to be:
<li><a href="#first">First</a></li>
<li><a href="#second">Second</a></li>
<li><a href="#third">Third</a></li>
CodePudding user response:
You can find all h3
elements that have an id
using the selector h3[id]
(a combination of a tag selector and attribute presence selector), and then map it to the structure you want. For instance:
const headers = $("h3[id]").get().map(element => ({id: element.id, text: $(element).text()}));
Then use that array to produce the content you want; perhaps:
$(".headers-in-here").html(
headers.map(({id, text}) => `<li><a href="#${id}">${text}</a></li>`).join("")
);
Live Example:
const headers = $("h3[id]").get().map(element => ({id: element.id, text: $(element).text()}));
$(".headers-in-here").html(
headers.map(({id, text}) => `<li><a href="#${id}">${text}</a></li>`).join("")
);
<div class="headers">
<h3 id="first">First</h3>
<h3 id="second">Second</h3>
<h3>None</h3>
<h3 id="third">Third</h3>
<h3>None Do not Show</h3>
</div>
<div class="headers-in-here"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Or you could do that in one step, rather than using an intermediate array of objects, but you specifically mentioned wanting an array. Here's one step:
$(".headers-in-here").html(
$("h3[id]").get().map(element => `<li><a href="#${element.id}">${$(element).text()}</a></li>`).join("")
);
Live Example:
$(".headers-in-here").html(
$("h3[id]").get().map(element => `<li><a href="#${element.id}">${$(element).text()}</a></li>`).join("")
);
<div class="headers">
<h3 id="first">First</h3>
<h3 id="second">Second</h3>
<h3>None</h3>
<h3 id="third">Third</h3>
<h3>None Do not Show</h3>
</div>
<div class="headers-in-here"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>