I have a function that requires a HTML element to perform the action on. I request the DOM selector as a parameter
function(document.body);
where element is the DOM query but somewhere else in the function I need the query as a string. Is it possible to turn the object into it's original string type? And if so, how?
You can do it the other way around. Pass your function a selector string:
functionName('body')
And then retrieve the relevant DOM element using .querySelector():
var el = document.querySelector(string);
The approach you are using is not going to produce the right results consistently in my opinion.
Passing in the element is going to mean that the element must be found beforehand and also is going to practically prevent finding other elements of similar location due to a lack of information.
Passing in a selector is an option, and then using that going forward if you need to find a similar set of elements but sometimes the selector is too complex to be placed in one string - for example if it needs filtering or some other metric.
Your best bet is to accept a callback function that returns the desired element or set of elements when you are dealing with complex selectors or locations for elements. It can simply return the same element each time if it is basic, or if it is more complicated the callback can access the DOM, filter based on some metric, and then return the subset which at times is ideal.
A callback function will provide the full amount of support without needing to always have a conversion to query string which is not always possible for complex structures.
If I understand you correct you could to this
function (elem) {
if (typeof elem === 'string' || elem instanceof String) {
elem = document.querySelector(elem);
}
var target = elem.querySelector(...);
}
To get the HTML string of an element use 'innerHTML'.
Temporary parent:
var div = document.createElement("div");
Append desired element to parent:
div.appendChild(document.body);
Test result:
alert(div.innerHTML);
If you are trying to get the string of the resulting element of 'querySelector()':
div.appendChild(document.body.querySelector('yourClass'));
The temporary parent ensures that you get the tags for the element returned. Otherwise you would only get the string for its child elements. If you want to use 'querySelectorAll()', just loop over the returned node array.
Related
I am currently trying to figure out a way to get the ID of an element, depending on whether its class contains something. I'm not sure if there's a better way to do it than I currently am, but having looked around nothing fits exactly the need I have. The code I currently have is, where I am looking for a div element whose class contains the string "one" but is not limited to that. Currently there is only one element containing this string but the alert provides me with [Object NodeList] (I may well be overcomplicating this):
$idToMove = document.querySelectorAll('div[class^="one"]');
alert($idToMove);
document.querySelectorAll() Returns a node list (kind of like an array), if you are sure there will only ever be one you have a couple options.
1) Use .querySelector instead:
// returns the first node that matches
var elm = document.querySelector('div[class~="one"]');
console.log(elm.id);
2) Access the first element in the returned list:
// returns all nodes that match
var elms = document.querySelectorAll('div[class~="one"]');
console.log(elms[0].id);
Make sure to null check returns of .querySelector and length check returns of .querySelectorAll.
Notice also, that I use ~= and not ^=. You can read on the MDN about the difference between all the equality operators. But for these two:
[attr~=value]
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".
[attr^=value]
Represents an element with an attribute name of attr and whose first value is prefixed by "value".
First get element from DOM and than from that element get id attribute:
1- If you need only first element then use querySelector like this:
let elms = document.querySelector('div[class~="one"]')[0].id
console.log(elms)
2- If you need all element those have this class then use querySelectorAll like this:
let elms = document.querySelectorAll('div[class~="one"]')
for(let i=0; i<elms.length; i++)
{
console.log(elms[i].id)
}
I think with "*" it works in more cases
document.querySelector('div[class*="words"]')
i tried it works absolutely amazing
window.frames[0].document.querySelector('td[id*="sss"]')
I have an array of elements I would like to keep on the page that I generated this way. The tricky part is that I need to preserve these elements parents and children.
var maps = document.querySelectorAll("[id^=map]")
I'd like to use jQuery's filter to remove all divs except those contained in the array from the page. I can't quite get it it to work though. I tried:
var all = $("div").get()
$(all)
.filter(function( index ) {
return $.inArray(this, maps) === -1;
}).remove()
That removed every element from the page. I figured that it was eliminating parent divs and their children regardless of whether the children were desired. I tried putting another filter function within the function, adding some nested conditionals, but it started to become a huge nonfunctional mess. Is there a more elegant way to do this? I don't necessarily need to use .filter().
Part of it may be that you are not returning a value from your filter function.
But if I understand you correctly, you can just look at the element and all of its contents:
$(all)
.filter(function( index ) {
$this = $(this);
return !($this.is("[id^=map]") || $this.find("[id^=map]").length > 0);
}).remove()
You can try using complex css selectors in the first place, like this:
$('div:not(div:has(.keep), div.keep)').remove();
http://jsfiddle.net/e_neko/k0bq6gzx/
This locates required elements and removes others in one pass.
anyone know where can I get information about this Type of selection in jquery
I found it in a .js file and I want to know about it.
I focus on Jquery api doc but in vain I dont find it.
var obj=$('#id1');
var t = $('.slidenews',obj).length;
exactly that what I want to know about.
var t = $('.slidenews',obj).length;
$('...', element) looks for ... in element instead of the whole document. So in this case, it will look for all elements with class slidenews in the #id1 element.
.length returns the number of such elements found
Therefore, if obj contains the element with ID id1, then $('.slidenews',obj).length returns the number of elements with class slidenews that are contained inside the element with ID id1.
Relevant documentation:
jQuery(selector, [context])
selector
Type: Selector
A string containing a selector expression
context
Type: Element or jQuery
A DOM Element, Document, or jQuery to use as context
length
Description: The number of elements in the jQuery object
$('.slidenews',obj) is basically context selector. It will be converted into obj.find('.slidenews') and .length returns the no of such elements
Reference
Selector Context
By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function.
It same like:
obj.find('.slidenews')
In your case: obj - must be DOM object. if obj is falsy it will be replaced to document
as all you know
$("#ID")
returns the element having ID.
but this code always return even there's no element.
alert($("#htrBuyerCouponNotice"));
alert(document.getElementById("htrBuyerConponNotice"));
in this case.
those two line results are diffrent.
I want to check whether there is an element has htrBuyerCouponNotice.
document.getElementByID return null if there's no element.
You can check the length property of the jQuery object to determine the number of matched elements, e.g.:
alert($(selector).length);
You can use it directly on if statements e.g.:
var $el = $(selector);
if ($el.length) { // only 0 will coerce to false
// ...
}
But most of the time you don't really need to know if the selector matched elements or not, because the jQuery built-in methods will be simply ignored, e.g.:
$('#nonExistent').hide();
The above statement will not cause any error even if the element was not found.
jQuery has also the size method, but I would recommend you to use the length property directly since it's publicly accessible, the size method is slightly slower since it is only a function that returns the value of length property.
because jQuery returns a list of selected elements, if there are no elements, you still get a return - its just a empty list.
check for $('#someID').length - should work if i remember corretly
When selecting elements, jQuery will always return an array of matching elements. In your case, $('#htrBuyerCouponNotice') is probably returning an empty array. Instead, check $('#htrBuyerCouponNotice').length.
Andrew
Try:
$("#htrBuyerCouponNotice").size()
It'll be zero if there's no nodes with that identifier, 1 if there is.
Currently I'm unit testing the following code:
if ($(selectedElement).innerText == 'blah')
{
// do something
}
with selectedElement being an anchor object selected from the UI.
In my test code, I have created a DOM structure which has that anchor in the proper position ready to be selected. The problem here is that since selectedElement is originally a javascript object, I need to convert the anchor I got from the DOM structure (which is a JQuery object) in order to get into the above condition.
I have tried the following, with no success:
// DOM structure using HtmlDoc
/*:DOC += <span id='testSpan' class='testSpanClass'><a href='#' id='selectedElem'>blah</a></span> */
selectedElement = $('#selectedElem')[0];
My goal is to be able to use a normal Javascript object to satisfy the condition, and also be able to switch it back to a jQuery object to satisfy conditions further down the function. But if there is a better approach I'll give it a go.
Does anyone have any ideas on how to go about this problem?
EDIT: Is there a solution that does not require changing of the code? selectedElement is actually a global variable.
Thanks.
I am not sure what browser you are testing in, but innerText is an IE only property. Since you are already using jQuery, I would suggest you just call the .text() method on the selected element like this:
selectedElement = $('#selectedElem')[0]; // Get DOM element
if ($(selectedElement).text() == 'blah')
{
// do something
}
You're method of getting the DOM object is fine: $('#selectedElem')[0] or $('#selectedElem').get(0) are equivalent, but the first one is faster in large loops.
jQuery's get method returns the original DOM elements for that jQuery object.
I think perhaps you need to use $('#selectedElem').get(0)
can you use jquery's .html() ?
if ($(selectedElement).html() == 'blah')
{
// do something
}
otherwise, without changing code:
var selectedElement = $('#selectedElem')[0];
if (selectedElement.innerHTML == 'blah')
{
// do something
}