0

I am using nodejs and have a variable with stored html code. To manipulate the content, I would like to get all defined ids. I tried to use jquery, but I am not quite familiar with the framework. I tried something like this:

const { JSDOM } = require( "jsdom" );
const { window } = new JSDOM( "" );
const $ = require( "jquery" )( window );

let Ids = [];
$(myHtmlCode).find('*').each(function(){ IDs.push(this.id); });

The output looks like: [ 'id1', '', '', 'id2', '', '', '', 'id3', '', 'id4', '', '' ]

Is there a better way to do that?

Would be happy for some help. Thanks!

1
  • Side note: You've used Ids and IDs. JavaScript identifiers are case-sensitive, they need to match. I assume this is just an error retyping the code for the question (copy and paste is generally best). Commented Jul 7, 2021 at 7:32

1 Answer 1

3

Search only for elements that have an id attribute: .find("[id]").

If you want to defend against elements with an id attribute that's empty (<div id> or <div id="">), you could add a check before push: if (this.id) { IDs.push(this.id); }, or you can do .find("[id][id!='']").

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.