I am trying to figure out if there is a way (without using any loops like each etc..) to look up element that has specific value, something like
var myElment = $('.container');
var child = $('.container-child');
myElement.find(child /* That has value of test */);
value is related to .val() of child element, so text inside it.
By the Attribute Equals Selector which is [attr=value].
So, to do that, just use
$(".container .container-child[value='test']")
Related
I want to apply a select criteria to a node I have fetched using a jQuery:
let objDIV = $("#selindividual").parent();
Now that I have the DIV I want to apply the following to it:
button:contains(\"Submit\")
If I was writing this in a node that contains buttons the query might look like this:
$("#idofnode button:contains(\"Submit\")")
So the question is how do I do the above when I have the node already?
You can use find():
let $objDIV = $("#selindividual").parent();
var $button = $objDIV.find('button:contains("Submit")');
children() would also work, it would just depend what relation the button is to the selected element and how far you want to traverse down the DOM to find it.
I am writing a small library where I am in need of selecting a relative element to the targeted element through querySelector method.
For example:
HTML
<div class="target"></div>
<div class="relative"></div>
<!-- querySelector will select only this .target element -->
<div class="target"></div>
<div class="relative"></div>
<div class="target"></div>
<div class="relative"></div>
JavaScript
var target = document.querySelectorAll('.target')[1];
// Something like this which doesn't work actually
var relativeElement = target.querySelector('this + .relative');
In the above example, I am trying to select the .relative class element relative only to the .target element whose value is stored in target variable. No styles should apply to the other .relative class elements.
PS: the selectors can vary. So, I can't use JavaScript's predefined methods like previousElementSibling or nextElementSibling.
I don't need solution in jQuery or other JavaScript libraries.
Well it should be ideally:
var relativeElement = target.querySelector('.relative');
But this will actually try to select something inside the target element.
therefore this would only work if your html structure is something like:
<div class="target">
<div class="relative"></div>
</div>
Your best bet would probably in this case be to use nextElementSibling which I understand is difficult for you to use.
You cannot.
If you insist on using the querySelector of the subject element, the answers is there is no way.
The spec and MDN both says clearly that Element.querySelector must return "a descendant of the element on which it is invoked", and the object element you want does not meet this limitation.
You must go up and use other elements, e.g. document.querySelector, if you want to break out.
You can always override Element.prototype.querySelector to do your biddings, including implementing your own CSS engine that select whatever element you want in whatever syntax you want.
I didn't mention this because you will be breaking the assumption of a very important function, easily breaking other libraries and even normal code, or at best slowing them down.
target.querySelector('.relative');
By using querySelector on the target instead of document, you scope the DOM traversal to the target element.
It is not entirely clear from your explanation, but by related i assume you mean descendant?
To get all target elements you can use
document.querySelectorAll('.target')
And then iterate the result
I found a way which will work for my library.
I will replace "this " in the querySelector with a unique custom attribute value. Something like this:
Element.prototype.customQuerySelector = function(selector){
// Adding a custom attribute to refer for selector
this.setAttribute('data-unique-id', '1');
// Replace "this " string with custom attribute's value
// You can also add a unique class name instead of adding custom attribute
selector = selector.replace("this ", '[data-unique-id="1"] ');
// Get the relative element
var relativeElement = document.querySelector(selector);
// After getting the relative element, the added custom attribute is useless
// So, remove it
this.removeAttribute('data-unique-id');
// return the fetched element
return relativeElement;
}
var element = document.querySelectorAll('.target')[1];
var targetElement = element.customQuerySelector('this + .relative');
// Now, do anything with the fetched relative element
targetElement.style.color = "red";
Working Fiddle
what's the different between using:
// assuming using elements/tags 'span' creates an array and want to access its first node
1) var arrayAccess = document.getElementsByTagName('elementName')[0]; // also tried property items()
vs
// assuming I assign an id value to the first span element/tag
// specifically calling a node by using it's id value
2) var idAccess = document.getElementById('idValue');
then if I want to change the text node....when using example 1) it will not work, for example:
arrayAccess.firstChild.nodeValue = 'some text';
or
arrayAccess.innerText/innerHTML/textContent = 'some text';
If I "access" the node through its id value then it seems to work fine....
Why is it that when using array it does not work? I'm new to javascript and the book I'm reading does not provide an answer.
Both are working,
In your first case you need to pass the tag name instead of the element name. Then only it will work.
There might be a case that you trying to set input/form elements using innerHTML. At that moment you need to use .value instead of innerHTML.
InnerHTML should be used for div, span, td and similar elements.
So your html markup example:
<div class="test">test</div>
<div class="test">test1</div>
<span id="test">test2</span>
<button id="abc" onclick="renderEle();">Change Text</button>
Your JS code:
function renderEle() {
var arrayAccess = document.getElementsByTagName('div')[0];
arrayAccess.innerHTML = "changed Text";
var idEle = document.getElementById('test');
idEle.innerHTML = "changed this one as well";
}
Working Fiddle
When you use document.getElementsByTagName('p'), the browser traverses the rendered DOM tree and returns a node list (array) of all elements that have the matching tag.
When you use document.getElementById('something'), the browser traverses the rendered DOM tree and returns a single node matching the ID if it exists (since html ID's are unique).
There are many differences when to use which, but one main factor will be speed (getElementById is much faster since you're only searching for 1 item).
To address your other question, you already have specified that you want the first element in the returned nodeList (index [0]) in your function call:
var arrayAccess = document.getElementsByTagName('elementName')[0];
Therefore, arrayAccess is already set to the first element in the returned query. You should be able to access the text by the following. The same code should work if you used document.getElementById to get the DOM element:
console.log(arrayAccess.textContent);
Here's a fiddle with an example:
http://jsfiddle.net/qoe30w2w/
Hope this helps!
Here's how I append the value:
$('<div>someText</div>').appendTo(self);
And here's how I want to remove it:
$(self).remove('<div>someText</div>');
The appending works, the removing doesnt. What am I doing wrong?
The .remove() function takes a selector to filter the already matched elements, not to match elements inside of them. What you want is something like this:
$(self).find('div:contains(someText)').remove();
That will find a <div> element containing the text someText inside of whatever element self is, then removes it.
The API http://api.jquery.com/remove/ sais that a selector is required.
Try $(self).remove('> div');
This will remove the first childs of div.
You can use $(self).filter('div:contains("someText")').remove(); to remove a div with a specific content or $(self).find('> div').remove(); to remove the first childs of div.
EDIT: removed first version I posted without testing.
It most likely has to do with the scope of self. Since you've named it self I am assuming that you are getting this variable using $(this) on the click event. If that's the case, and you want to call the remove method, you can only do so from within the same function. Otherwise you need to either store the element in a variable or provide another selector to access it.
Example:
<div class="div1"></div>
this will be the div with the click event
$(document).ready(function(){
var self = null;
$('.div1').click(function(e){
self = $(this);
var itemToAdd = '<div>SomeText</div>';
$(itemToAdd).appendTo(self);
});
// to remove it
// this will remove the text immediately after it's placed
// this call needs to be wrapped in a function called on another event
$('.div1').find('div:contains(someText)').remove();
});
I want to search through my document, and find all inputs with title attribute, but at the same the title attribute can not be empty. So it should look for every input with title attribute that has at least one character in length.
Then I would like to make some event on those inputs (like add them some CSS class).
Is that even possible with jQuery or other javascript library?
I believe this would give you what you want:
$('input[title][title!=""]')
To apply css
$('input[title][title!=""]').addClass('class1 class2 class3');
http://jsfiddle.net/5hkAG/
$("input[title]").not('[title=""]')
var myInputs = [];
$("input").each(function() {
if($(this).attr("title").length > 0) {
myInputs.push(this);
// do other events as usual, using $(this) as selector for current input
}
});
// do something with myInputs, which is an array of all inputs with a title attribute