简体   繁体   中英

Javascript: Append Element to a Class Only on Specific .html File

New to JS. Let's say I have an index.html page that has a <div class="posts"> . I also have an about.html page that has a <div class="posts"> . They have the same css stylesheet linked to them, but I want the <div class="posts"> container to hold different content per page. The same script.js page is linked to both files.

If I create a new div using JS like such:

newDiv = document.createElement('div');
postContent = document.querySelector(".posts");
postContent.append(newDiv);

Is there a way to append the element ONLY to the <div class="posts"> on the about.html page, but not the index.html page?

I could just give the div on the about.html page a unique class name, but then the styles from the css sheet will not apply to the new class unless I manually add some duplicate styles for the new class name. I could also create a separate .js file just for the about.html page and only link it to that page.

However, in the scenario that I am trying to use this for, I will be creating many .html pages (think one for April 2021, one for May 2021, and on and on), so it is not feasible to keep using unique class names and adding more duplicate styles to my stylesheet for every single page, or to create new .js files for every single page.

How can I target an element to only be appended to the class on a specific .html page?

Apologies if this question has been asked before. I searched far and wide before asking here.

you can use ID attribute of the element. something like:

<div id="posts_of_about" class="posts">

and your js can be something like this:

newDiv = document.createElement('div');
postContent = document.querySelector("#posts_of_about");
postContent.append(newDiv);

its only one of a lot of solutions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM