getElementsByClass and appendChild - javascript

just brushing up on my javascript skills and trying to figure out why getElementsByClass isn't working for my code. The code is pretty simple. Upon clicking a button "clicky", the script will create a child h1 element of div. It works perfectly fine when I use getElementById and changing the div class to Id but doesn't work when I change it to class.
I've tried, getElementsByClassName, getElementsByClass, getElementsByTagName and changing the div to the appropriate attribute but no luck.
<!doctype html>
<html>
<body>
<p>Click on button to see how appendChild works</p>
<button onclick="myFunction()">Clicky </button>
<script>
function myFunction(){
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);
document.getElementsByName("thistime").appendChild(first);
}
</script>
<div class="thistime">Hi</div>
</body>
</html>

You need to update your code from
document.getElementsByName("thistime").appendChild(first);
to
document.getElementsByClassName("thistime")[0].appendChild(first);
For reference - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Working code - http://plnkr.co/edit/k8ZnPFKYKScn8iYiZQk0?p=preview

You could use getElementsByClassName(), which is supported in IE9+:
document.getElementsByClassName("thistime")[0].appendChild(first);
But a better alternative may be querySelector(), which is supported in IE8+
document.querySelector(".thistime").appendChild(first);
Note that querySelector() uses CSS selector syntax, so you should place a dot (.) before the class.
Snippet:
function myFunction() {
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);
document.querySelector(".thistime").appendChild(first);
}
<p>Click on button to see how appendChild works</p>
<button onclick="myFunction()">Clicky</button>
<div class="thistime">Hi</div>

As you have noticed, the function is called getElementsByName with "elements" being a plural.
It returns a list of markups by their name (and not their css class).
You need to use the function that handles the class name, and get the first element of the array, or loop on all the results, depending on what you are looking for.

Related

Find element in document using HTML DOM

I need to be able to select and modify an element in an HTML document. The usual way to find an element using jQuery is by using a selector that selects by attribute, id, class or element type.
However in my case I have the element's HTML DOM and I want to find the element on my document that matches this DOM.
Important :
I know I can use a class selector or ID selector etc.. but sometimes the HTMLs I get don't have a class or an ID or an attribute to select with, So I need to be able to select from the element's HTML.
For example here is the element I need to find :
<span class='hello' data='na'>Element</span>
I tried to use jQuery's Find() but it does not work, here is the jsfiddle of the trial : https://jsfiddle.net/ndn9jtbj/
Trial :
el = jQuery("<span class='hello' data='na'>Element</span>");
jQuery("body").find(el).html("modified element");
The following code does not make any change on the element that is present in my HTML and that corresponds to the DOM I have supplied.
Is there any way to get the desired result either using native Javascript or jQuery?
You could filter it by outerHTML property if you are sure how browser had parsed it:
var $el = jQuery("body *").filter(function(){
return this.outerHTML === '<span class="hello" data="na">Element</span>';
});
$el.html("modified element");
el = jQuery('<i class="fa fa-camera"></i>');
This does not say "find the element that looks like <i class="fa fa-camera"></i>". It means "create a new i element with the two classes fa and fa-camera. It's the signature for creating new elements on the fly.
jQuery selectors look like CSS, not like HTML. To find the i element with those two classes, you need a selector like i.fa.fa-camera.
Furthermore $("document") looks for an HTML element called document. This does not exist. To select the actual document, you need $(document). You could do this:
$(document).find('i.fa.fa-camera').html("modified html")
or, more simply, you could do this:
$('i.fa.fa-camera').html('modified html');
You indicate in a comment to your question that you need to find an element based on a string of HTML that you receive. This is, to put it mildly, difficult, because, essentially, HTML ceases to exist once a browser has parsed it. It gets turned into a DOM structure. It can't just be a string search.
The best you can do is something like this:
var searchEl = jQuery('<i class="fa fa-camera"></i>');
var tagName = searchEl.prop('tagName');
var classes = [].slice.apply(searchEl.prop('classList'));
$(tagName + "." + classes.join('.')).html('modified html');
Note that this will only use the tag name and class names to find the element. If you also want IDs or something else, you'd need to add that along the same lines.
You should use Javascript getting the elements by something like
document.getElementById...
document.getElementsByClassName...
document.getElementsByTagName...
Javascript is returning the elements with the Id, Class or Tag Name you chose.
You can get en element with document.querySelector('.fa-camera')
with querySelector you can select IDs and Classes
You can simply refer to it by its class names.
$('.fa.fa-camera').html("modified html");
Similar to this answer https://stackoverflow.com/a/1041352/409556
Here is a full example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.fa.fa-camera').html("modified html");
});
</script>
</head>
<body>
<i class="fa fa-camera"><h1>Some HTML</h1></i>
</body>
</html>`
The one thing that you could use is to check attributes (class and id goes here too in some way) that element have, and the build jQuery selector or DOM querySelector to find the element you need. The hardest part would be to find element based on innerHTML property - "Element" text inside it, for this one you'll probably have to grab all similar element and then search through them.
<span class='hello' data='na'>Element</span>
jQuery('body').find('span.hello[data=\'na\']').html('modified element')
Take notice of 'span' - that's tag selector, '.hello' - class, '[data="na"]' data attribute with name of data.
Jsfiddle link here that extends your example;

Hide DIV element with onclick command

Thanks to anyone who helps me solve this issue.
So the issue is I'm trying to hide an element (by class) with an onclick event using a button. But I am unable to do so.
Here's the code on jsfiddle http://jsfiddle.net/1tpdgrnj/
Here's the code for those who wish to help me here:
HTML:
<div class="box">Hide on button click!!
<button onclick="close();">Close</button>
Javascript:
function close() {
document.getElementsByClassName("box").style.display = 'none';}
UPDATE
Refer to the answer below and to the jsfiddle to see how it's different.
See this fiddle
Change your javascript as follows
function myFunction() {
document.getElementsByClassName("box")[0].style.display = 'none';
}
First change that should be done is, rename your function name, as close is a keyword in Javascript.
Second one is that, document.getElementsByClassName() returns an array and thus to get the first element you should use the index position 0.
According to the docs
The Element.getElementsByClassName() method returns a live
HTMLCollection containing all child elements which have all of the
given class names. When called on the document object, the complete
document is searched, including the root node.
Read more about it here
You can use Jquery
<div class="box">Hide on button click!!
<button class="close">Close</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".close").click(function(){
$(this).parent().hide(); return false;
});
});
</script>
Check this fiddle
You can also do this easily with jQuery.
$("#hide").click(function(){
$(".box").fadeOut(150);
});

innerHTML isn't working with getElementsByClassName

I'm just a beginner. And I'm trying to use innerHTML.
I think I wrote proper code, but it doesn't work.
When I click the trigger, the page becomes white and showing the statut : 'connecting'
I don't know where is the problem
Please someone help me.
Here are my codes.
HTML CODE
<div class = "head">
<nav>
<a onClick="open()">
<div class = "body">
<div class = "bodyL">
<div class = "newsPnT">
JAVASCRIPT CODE
function open() {
document.getElementsByClassName('newsPnT').innerHTML = "asdfasdfasdf";
}
What is the problem with my code?
PS: I'm using Firefox Aurora. When I click the trigger, the 'debugger > sources' says, 'waiting for sources.'
getElementsByClassName() returns array with elements.
Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.
So you need iterate array and set innerHTML like this i.e.
var elements = document.getElementsByClassName('myClass');
Array.prototype.forEach.call(elements, function(element) {
element.innerHTML = 'Your text goes here';
});
Also a little bonus JSFiddle
the className 'open' seemed to the keyword of javascript.
I changed the className from 'open' to 'openThis'and that came to be a solution of the problem.

How to change a css class style through Javascript?

According to the book I am reading it is better to change CSS by class when you are using Javascript. But how? Can someone give a sample snippet for this?
Suppose you have:
<div id="mydiv" class="oldclass">text</div>
and the following styles:
.oldclass { color: blue }
.newclass { background-color: yellow }
You can change the class on mydiv in javascript like this:
document.getElementById('mydiv').className = 'newclass';
After the DOM manipulation you will be left with:
<div id="mydiv" class="newclass">text</div>
If you want to add a new css class without removing the old one, you can append to it:
document.getElementById('mydiv').className += ' newClass';
This will result in:
<div id="mydiv" class="oldclass newclass">text</div>
Since classList is supported in all major browsers and jQuery drops support for IE<9 (in 2.x branch as Stormblack points in the comment), considering this HTML
<div id="mydiv" class="oldclass">text</div>
you can comfortably use this syntax:
document.getElementById('mydiv').classList.add("newClass");
This will also result in:
<div id="mydiv" class="oldclass newclass">text</div>
plus you can also use remove, toggle, contains methods.
If you want to manipulate the actual CSS class instead of modifying the DOM elements or using modifier CSS classes, see
https://stackoverflow.com/a/50036923/482916.
I'd highly recommend jQuery. It then becomes as simple as:
$('#mydiv').addClass('newclass');
You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();
The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.
$('div').addClass('newclass');
$('.oldclass').addClass('newclass');
The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.
use the className property:
document.getElementById('your_element_s_id').className = 'cssClass';
There are two ways in which this can be accomplished using vanilla javascript. The first is className and the second is classList. className works in all browsers but can be unwieldy to work with when modifying an element's class attribute. classList is an easier way to modify an element's class(es).
To outright set an element's class attribute, className is the way to go, otherwise to modify an element's class(es), it's easier to use classList.
Initial Html
<div id="ID"></div>
Setting the class attribute
var div = document.getElementById('ID');
div.className = "foo bar car";
Result:
<div id="ID" class="foo bar car"></div>
Adding a class
div.classList.add("car");// Class already exists, nothing happens
div.classList.add("tar");
Note: There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.
Result:
<div id="ID" class="foo bar car tar"></div>
Removing a class
div.classList.remove("car");
div.classList.remove("tar");
div.classList.remove("car");// No class of this name exists, nothing happens
Note: Just like add, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.
Result:
<div id="ID" class="foo bar"></div>
Checking if a class attribute contains a specific class
if (div.classList.contains("foo")) {
// Do stuff
}
Toggling a class
var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed
classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added
.toggle has a second boolean parameter that, in my opinion, is redundant and isn't worth going over.
For more information on classList, check out MDN. It also covers browser compatibility if that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.
document.getElementById("my").className = 'myclass';
You may also be interested in modifying it using jQuery:
http://api.jquery.com/category/css/
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").addClass(function(){
return "par" ;
});
});
</script>
<style>
.par {
color: blue;
}
</style>
</head>
<body>
<div class="test">This is a paragraph.</div>
</body>
</html>

Why is document.getelementbyId not working in Firefox?

I can't figure out why document.getElementById is not working in Firefox:
document.getElementById("main").style.width = "100";
When I check in Firebug it says:
TypeError: document.getElementById("main") is null
Does anybody know why this is happening?
EDIT: Unfortunately, the "body" element was a bad example. I changed it to another element with an id of "main".
put your script before
</body>
Or, if you use your script in <head> you may change code:
$(document).ready(function() {
//enter code here.
});
Did you set the id of the <body> element to "body":
<body id="body" ...>
Update:
Check if the following example works for you: http://jsbin.com/uyeca/edit
Click the Output tab to see the result (which should be a DIV with width 600px).
https://developer.mozilla.org/En/DOM/Document.getElementById
Simply creating an element and
assigning an ID will not make the
element accessible by getElementById.
Instead one needs to insert the
element first into the document tree
with insertBefore or a similar method,
probably into a hidden div.
var element = document.createElement("div");
element.id = 'testqq';
var el = document.getElementById('testqq'); //
el will be null!
I had the same prob...I was trying to use "getElementById" without the main structure of the HTML page-- tag was missing.
After adding in my page it worked fine...I was working on a script that was supposed to be embeded on other sites--widget sort of thing.

Categories

Resources