Simple GetElementById issue - javascript

I'm new to javascript I'm having a very simple problem. I just don't get what's going on.
I just want to add a class to a <div> tag but it's not working
This is my javascript:
var element = document.getElementById("main");
element.classList.add("hidden");
Here's my fiddle:
http://jsfiddle.net/72o6j6r0/

You are close, the method document.getElementById() returns an HTML element by using the id of the element
HTML:
<html>
<body>
<div id="main">
This is my main content to be hidden
</div>
</body>
</html>
Javascript:
var element = document.getElementById("main");
element.classList.add("hidden");
If you want to use the class attribute to select your elements rather than the id you can use:
document.getElementsByClassName()
and then loop over the results
Here is a JSFiddle example:
http://jsfiddle.net/mko3uf9f/

Related

Select child element from parent - Plain Javascript

I need some help with Javascript.
What I try to do is move an element to another element.
Normaly I can use the queryselector but in this case I can not because there are multiple elements with the class "destination". To get the result what I want I need select first the parent element "catalog-item" and after that the child "destination".
I need some help to get the right element catalog-item->destination
<div id="catalog-item">
<div class="destination">
</div>
</div>
<div id="move"></div>
<script type="text/javascript>
var itm = document.getElementById("move");
var cln = itm.cloneNode(true);
itm.remove();
document.getElementById("catalog-item").children(".destination").appendChild(cln);
</script>
Who can help me?
You can select the child element with querySelector by writing document.querySelector("#catalog-item .destination"). Just put a space between them.

adding css class in <body> javascript

I am facing an issue in jquery , i want to add a css test class in body tag.
My code
(function($) {
if($("#root").length){
$("#root").closest("body").addClass('co_queue_page'); //not working
}
})(jQuery);
<div class="row"> //react code
<div id="root">
<div>
<header>
<div class="container-fluid">...</div>
</header>
</div>
</div>
</div>
what should i do? some help me help?
You don't need to use .closest() method, there is only one tag in HTML document, just do it by selecting the <body> directly:
(function($) {
if($("#root").length){
$("body").addClass('co_queue_page');
}
})(jQuery);
To select the <body> element, using jQuery, you can use:
const element = $(document.body);
const element = $("body");
Then you can use .addClass() to add your custom class dynamically, like so:
element.addClass("co_queue_page");
jQuery fiddle working example
This can be also done without any jQuery, accessing the body DOM element through the document object:
const element = document.body;
element.classList.add("co_queue_page");
Vanilla JS fiddle working example
Please add the below code:
$("body").addClass("class_name");

Getting an element HTML

I have HTML document like this
<html>
<head></head>
<body>
<div id="test_id"> First element </div>
<div> Second element </div>
</body>
</html>
I can access first div element via getElementById but can I access somehow Second element?
You can use Document.querySelectorAll() with specific index like the following way:
var secondDiv = document.querySelectorAll('div')[1];
console.log(secondDiv);
<html>
<head></head>
<body>
<div id="test_id"> First element </div>
<div> Second element </div>
</body>
</html>
You can try :
var x = document.getElementById("test_id").nextSibling
Method 1:
get Parent Element then count to your desired element then read by it name,
document.getElementById("test_id").parentElement.getElementByTagName("div")[0].innerHTML;
Method 2:
direct count to div like mentioned but in some cases it won't works
document.getElementByTagName("div")[1]
document.getElementsByTagName("div") returns all divs into a HTMLCollection object, the first div is 0 second div is 1:
var second = document.getElementsByTagName("div")[1]
console.log(second.innerHTML)
<html>
<head></head>
<body>
<div id="test_id"> First element </div>
<div> Second element </div>
</body>
</html>

Select element in Jquery selector by class name and convert it back to Jquery object

I don't understand why when i looking for how to get an element in list of element selected by class name like in traditional JS, I've always seen complicated answers .
document.getElementsByClassName('anyclass')[1]
so, i have found out myself that i cant do that (may be its the wrong approach)
$('.anyclass')[1]
but i get a DOM element! so logically i tried
$('.anyclass')[1][0]
and it doesnt work 'TypeError: $(...)[0][0] is undefined'
Anyone can explain why ? thank you!
I think you need .eq(index)
var secondElement = $('.anyClass').eq(1); //jQuery object
var domElement = secondElement[0]; //DOM element
console.log(secondElement, domElement)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='anyClass'>1</div>
<div class='anyClass'>2</div>
var elm = document.createElement("div");
var jelm = $(elm); //convert to jQuery Element
var htmlElm = jelm[0]; //convert to HTML Element
The :first pseudo-class is equivalent to :eq( 0 ). It could also be written as :lt( 1 ). While this matches only a single element, :first-child can match more than one: One for each parent.
here
$('.anyclass:first)
Quick example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$($(".t")[1]).css("background-color", "yellow");
});
</script>
</head>
<body>
<p class=t>This 1.</p>
<p class=t>This 2.</p>
<p class=t>This 3.</p>
</body>
</html>
'
$('.anyclass')[0].attr("src"); you can use like this .
after your comment:
$(".anyclass")[1] is a DOM element not a jquery object. Simply wrap it as jquery $($("td")[1]).width()

Adding div tag below another div tag

I have a div tag with class divstudent, lets say this is div1 tag. Now I want to create another div tag div2 dynamically below this div1 tag, not inside of the div1 tag. I want to create outside of div1 tag using javascript. How can I do that?
"div1"
<div class="divstudent"></div>
<!-- i want to be like this -->
<!-- "div1" -->
<div></div>
<!-- "div2" -->
<div></div>
<!-- "div3" -->
<div></div>
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
Try something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Divs creator</title>
<script type="text/javascript">
window.onload = function () {
var divReference = document.querySelector('.divstudent');
var divCounter = 0;
divReference.addEventListener('click', function () {
var divToCreate = document.createElement('div');
divToCreate.innerHTML = ++divCounter;
divReference.parentNode.appendChild(divToCreate);
}, false);
}
</script>
</head>
<body>
<div class="divstudent">
<input type="button" value="add div below divstudent">
</div>
</body>
</html>
Since this is tagged jquery, just use .after()
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
There are many ways to do this. One significant difference in methods is if you choose to create the elements first using Document.createElement() and then insert the elements, or create and insert the elements in one step using one of the methods that allows you to insert HTML text.
Because it is simpler, but not necessarily better, the examples below show creating and inserting the two <div> elements in a single step using methods that allow inserting HTML text into the DOM.
JavaScript:
One is to use insertAdjacentHTML() and specify that it is to be inserted afterend of the element you are using.
document.querySelector() is used to find the first <div class="divstudent">. Then insertAdjacentHTML() is used to add the additional <div> elements. Element.removeAttribute() is then used to remove the class="divstudent". Note: if we had just wanted to set teh class to something different, even '', then we could have used Element.className.
NOTE: In this answer, text identifying each <div> has been added to the <div>s so there is something visible in the examples in this answer.
//Find the first <div class="divstudent"> in the document
var studentDiv = document.querySelector('div.divstudent');
//Insert two new <div> elements.
studentDiv.insertAdjacentHTML('afterend','<div>2</div><div>3</div>');
//Remove the class="divstudent"
studentDiv.removeAttribute('class');
<div class="divstudent">1</div>
jQuery:
While your question is tagged jQuery, a comment you posted implies you are just using JavaScript. Thus, I am not sure if jQuery works for you.
If you want to use jQuery, then you can use .after() to add the <div> elements. You can then use .removeAttr() to remove the class="divstudent".
// Get the first <div class="divstudent">.
// Store it in a variable so we only walk the DOM once.
var $studentDiv = $('div.divstudent').eq(0);
//Add the two new <div> elements
$studentDiv.after('<div>2</div><div>3</div>');
//Remove the class="divstudent"
$studentDiv.removeAttr('class');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divstudent">1</div>
You create a new div (in js), then just append your newDiv, after the target div. Something along the lines of in vanilla js:
// Create your new div
var newDiv = document.createElement("div");
newDiv.innerText = "New Div!";
// Grab the div you want to insert your new div after
var target_div = document.querySelector("div.divstudent");
// Insert newDiv after target_div (before the thing after it)
target_div.parentNode.insertBefore(newDiv, target_div.nextSibling);

Categories

Resources