Append an element inside a specific div's element using Javascript - javascript

I know how to append an element inside another element, but how do I specify which class I want to append it to?
For example:
<div class="main" id="11">
<div class="somethingelse>
<div class="moreThings">
/*How to append to this class?*/
</div>
<div class="extraThings">
</div>
</div>
</div>
What I have is something like this:
var x = document.createElement("IMG");
x.setAttribute("src", "../truck.png");
document.getElementById(order_id).appendChild(x);
document.getElementById("btn_transport_"+order_id).style.display = "none";
There could be hundreds of classes with same name which is why I need to define them by id.
At the moment I am appending the img under everything other divs, but I would like to append it inside "morethings". How would I do that?

You could do something like this:
document.getElementById(order_id).getElementsByClassName("moreThings")[0].appendChild(x);
Make sure getElementsByClassName("moreThings") returns at least one element.
You can find out more about getElementsByClassName(...) from HERE. The gist of it is:
Returns an array-like object of all child elements which have all of the given class names

You could use document.querySelector. It allows CSS-like selectors. In your case it could look like
const myElementToAppendTo = document.querySelector('#myID .morethings');
myElementToAppendTo.appendChild(x);

Related

How add ID to HTML href with javascript

I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>

How to get elementsByClassName and then inside getElementById

Hi I'm rewriting a script from jQuery to pure JS and I don't know how else could i write this.I want to get attribute of element inside class 'form-basket' with id 'przecenajs' I know getElementsByClassName returns object of elements, and that's probably why I get the error:document.getElementsByClassName(...).getElementById is not a function
but I'm not into JS that much so i might be wrong
price = document.getElementsByClassName('form-basket').getElementById("przecenajs").getAttribute("data-procent");
That because getElementsByClassName returns a HTMLCollection object.
You probably want to use querySelector function:
document.querySelector('.form-basket #przecenajs')
console.log(document.querySelector('.form-basket #przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
or
document.getElementById('przecenajs')
console.log(document.getElementById('przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
Resources
document.querySelector()
Document.getElementsByClassName()
You do not have to select the form-basket first. Since IDs should only be used once inside a document, you can simply selct by id like so:
document.getElementById("przecenajs").getAttribute("data-procent");
I assume you are searching for more than only one tag, because if you wouldn't you could just use document.getElementById() so I think these lines do the job you want, you have to manually create the list with all the attributes to replicate the jquery behaviour:
var priceList = [];
document.querySelectorAll(".form-basket #przecenajs").forEach( (element) =>{
priceList.push(element.getAttribute("data-procent"));
});

JQuery clone insertafter

I cloned a html element.
var $clone = $('.rules-if-field-container-'+if_counter).clone(true);
But now I want to append a div when the div is cloned.
I tried this:
$clone.append('<div class="append_or_'+inc_counter+'"> </div>').insertAfter('rules-if-field-container-'+inc_counter);
But doesn't give me the correct result.
It gives me this result:
<div class="box box-warning box-solid rules-if-field-container-1"><div class="append_or_1"> </div></div>
But it must be like this:
<div class="box box-warning box-solid rules-if-field-container-1"></div>
<div class="append_or_1"> </div>
How can I perform a insertAfter when I cloned an element?
In that case append() is not suitable for your needs, as it creates the content you specify as a child element of the target.
Instead you can first add the clone to the DOM, then use after() to add the second div. Try this:
$clone
.insertAfter('.rules-if-field-container-' + inc_counter)
.after('<div class="append_or_' + inc_counter + '"> </div>');
Also note that I would strongly suggest you don't use incremental class names. They quickly become a pain to maintain, and go completely against the point of classes, which is to allow grouping of related elements.
From jQuery docs.
The .append() method inserts the specified content as the last child
of each element in the jQuery collection (To insert it as the first
child, use .prepend()).
I think you need after instead.
Insert content, specified by the parameter, after each element in the set of matched elements.

What is the best practice to get a child of an element in HTML?

Something like get an variable out of class.
ParentElement.someId.someId..
If i have something like that in css:
#someId #aaa #bbb
{
...
}
#someOtherId #aaa #bbb
{
...
}
and i want to get only the element under "#someId".
Something like
getElementById("someId aaa bbb");
would be great, unfortunately this one doesn't work.
Any ideas?
If you have given an id to the element, you can say
document.getElementById(childId)
Id must be unique in the document.
In your scenario, what I think you are having element with same Id at multiple places. Either you can user class instead of id.
I assume you want to get the element in javascript, or what do you mean by "getting" in HTML?
<div id="box">
<div>Child element</div>
<div>Child element</div>
</div>
You can access a specific element by getElementById('box'); and you can access its children by getElementById('box').children. So the first child would be getElementById('box').children[0] for example.
Did that help you ?
Id's are unique within the document so your ParentElement.someId.someId can simply be translated to document.getElementById(childId).
Regarding the sample CSS you posted, please note that you cannot have both situations in the same HTML at the same time, you can stylise differently based on the DOM hierarchy though. With this in mind, you can use the same document.getElementById(childId) call.
ID should be unique, so you really shouldn't have elements with the same ID over and over, instead you can use class.
To access the element though, first you get the parent:
var parent = document.getElementById("someId");
Then use querySelector on parent to get the desired element:
var element = parent.querySelector('.ELEMENT_CLASS');
And if it's id then:
var element = parent.querySelector('#ELEMENT_ID');

Save the parents children in a var to append later

I have a markup in one of my website pages as follows:
<div id="mainPage">
<div>
<div><ul><li>etc.</li></ul>
</div>
<div>
<div><ul><li>etc.</li></ul>
</div>
</div>
What the above means is that there's a main div in my website which has the content. I want to take all the children of the particular div and save it in a var, since I want to use that var later for something like $('resurrectPage').append(someVar); where someVar has the dom elements from the main page div.
How can all the children of a particular element be selected and added to a var?
$('#mainPage').html() would give you the entire thing in a string "<div>
<div><ul><li>etc.</li></ul> </div> <div> <div><ul><li>etc.</li></ul> </div>"
$('#mainPage').children() would give you immidiate children [div,div]
$('#mainPage').find('.div') would giv =e you all the divs inside it [div,div,div,div]
if #mainPage is your main div, you can get of it's children by
var someVar = $('#mainPage').children();
Official api page
I think you're looking for jQuery detach method...
http://api.jquery.com/detach/
It will remove an element and store its contents, ready to be re-appended:
var a = p = $("a").detach()
If you only need the HTML you can save the HTML: var someVar = $("#mainPage").html(); and then append the HTML with the code you already have. Please tell me if I have misunderstood your question.

Categories