i cached a <div> in an object, and i want to use .find() method to get its style property without touching the DOM
lets say:
<body>
<div id="one" style="visibility:visible;">
</div>
</body>
<script>
var cache = {
cacheBody: $("body").find("div#one")
}
//i want to do this
chach.cacheBody.find("style") //or chach.cacheBody.find("visibilty")
</script>
the importent thing is that, i dont want to use jquery on DOM for this.
but on the cached object
var cache = {
cacheBody: $("div#one")
}
//i want to do this
var style= cache.cacheBody.attr("style"); //or chach.cacheBody.find("visibilty")
console.log(style);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" style="visibility:visible;">
</div>
I believe your use of .find() here is incorrect. It is used to traverse the DOM and "find" nodes that match the parameter given.
What you may be after is .attr(). If you want to get the style specific to that DOM Node which was given inline. Otherwise if you want the entire CSSStyleDeclaration object, you can use:
$('div#one')[0].style // instead of $('div#one').attr('style')
To get a complete object of all applied (and not applied) styles to the Node.
This is not as browser compatible as the rest of the code as it does not make use of jQuery for retrieving the actual object.
Related
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"));
});
Is it possible to get a node's top-level tag html via the dom api? To be clear, if I have
<div data-x="a">
<span>Hello</span>
</div>
I want to just get back <div data-x="a">
Is a crude string matching on outerHTML the best I can do, or is there a fast and direct way to achieve what I want?
If you clone the node, the innerHTML property will be empty.
For your example, a shallow clone is appropriate (pass false or don't pass anything).
// get the div element
var element = document.querySelectorAll('div')[0];
// view the outerHTML of the element
console.log('original outerHTML', element.outerHTML);
// clone the element
var clone = element.cloneNode();
// view the outerHTML of the clone
console.log('outerHTML of clone', clone.outerHTML); // has what you want
<div data-x="a">
<span>Hello</span>
</div>
.cloneNode() on MDN
You can use the outerHTML to get all of it, and the innerHTML to get the stuff just inside. Then do a string replace on the outerHTML, replacing the innerHTML with an empty string, and doing the same for the end tag.
With the following code:
<div id="container">
<svg [attributes etc.]> ... </svg>
</div>
I would like to dynamically change the width and height of the SVG.
I have tried:
myObj = document.getElementById('container').getElementsByTagName('svg');
myObj.style.width = "400px";
but I get the error "undefined is not an object".
The SVG is loaded using a server-side include, and I can not modify it in any way, so I need to find a way to manipulate it from the outside.
I would prefer to avoid jQuery.
The reason you get that error is because myObj, the result of getElementsByTagName(), is a NodeList of elements since it can potentially return more than one element, and style is not defined on a NodeList. Not a particularly helpful error since it doesn't describe the actual problem...
Anyway, simply index off of that collection to get an element that you can work with:
myObj = document.getElementById('container').getElementsByTagName('svg');
myObj[0].style.width = "400px";
Alternatively, if you're sure you will only ever have one #container > svg, use querySelector() instead:
myObj = document.querySelector('#container > svg');
myObj.style.width = "400px";
getElementsByTagName returns the array-like collection object. So, you need to iterate over the collection for eg:
myObj = document.getElementById('container').getElementsByTagName('svg');
myObj[0].style.width = "400px";//myObj[0] refers to first found svg element
It may be possible to acheive this with css alone, providing you have access to that?
#container {
svg {
width: 400px;
}
}
How can I change the string inside action="somthing" I've tried using
document.getElementsByClassName
but it doesn't seems to change anything.
My HTML
......
.........
<div class="my_button button" action='play_car'></div>
.....
......
My Javascript
document.getElementsByClassName('my_button').action = "play_boat";
.......
......
I've also tried
HTML
<div id="test" class="my_button button" action='play_car'></div>
Javascript
var a= document.getElementById('test');
console.log(a);
It just returns null
"get element-s by class name" returns a collection, not a single element.
Returns an array of all child elements which have any of the given class names. When called on the document object, the complete document is searched, including the root node.
Assuming that there is only a single element returned, then:
var elementsWithClass = document.getElementsByClassName('my_button')
elementsWithClass[0].action = "play_boat";
However, it may be more appropriate to use a loop - class names are generally designed to be used with multiple elements, and IDs (along with getElementById) for singular/unique elements.
Unfortunately, getElementsByClassName is not supported in even as "recent" a browser as IE8. To handle this, use a cross-browser library (jQuery or your preference) or a polyfill.
getElementsByClassName will return an array of all elements. Use document.getElementById if you want to address only one element. Also getElementsByClassName isn't supported by older browser. If that's an issue, you can use jQuery instead.
If you have only one element with this class name, you can get the first item:
document.getElementsByClassName('my_button')[0].action = "play_boat";
if you have many, iterate over them:
for (var i in document.getElementsByClassName('my_button')) {
document.getElementsByClassName('my_button')[i].action = "play_boat";
}
Please, check if the place of the javascript code is after the elements with the class "my_button".
I have a div <div id="masterdiv"> which has several child <div>s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>s inside the master <div> using jQuery?
jQuery's empty() function does just that:
$('#masterdiv').empty();
clears the master div.
$('#masterdiv div').empty();
clears all the child divs, but leaves the master intact.
jQuery('#masterdiv div').html('');
Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.
$('#masterdiv div').empty();
Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.
I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
The better way is :
$( ".masterdiv" ).empty();
$("#masterdiv div").text("");
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();