How do I search nested divs using regex for class names - javascript

I want to search for nested divs like these in my DOM
<div class="two-columns some-other-class">
<div class="two-columns some-other-class">
</div>
</div>
I tried to search nested divs like this
$("div[class$='columns'] div[class$='columns']")
but it's not working :(

Use the Attribute Contains Selector:
$("div[class*='columns'] div[class*='columns']")
Edit:
If you want that exact functionality you might want to extend the jQuery selector engine:
$.extend($.expr[':'], {
classEndsWith: function(e, i, meta) {
var found = false
var classes = e.className.toLowerCase().split(' ');
var suffix = meta[3].toLowerCase();
$.each(classes, function(i, c) {
// Check if className ends with value in suffix
if (c.indexOf(suffix, c.length - suffix.length) !== -1) {
found = true;
return false;
}
});
return found;
}
});
var element = $('div:classEndsWith(columns) div:classEndsWith(columns)');
See JSFiddle.

$("div[class$='columns'] div[class$='columns']")
Is working. Check the fiddle

Related

A one-liner for finding the index of an element that has certain class within a jQuery set of elements?

I've got an arbitrary structure like this:
<h2>Foo</h2>
<p>Foo foo</p>
<p>Foofoo</p>
<h2>Bar</h2>
<h2 class=highlighted>Baz</h2>
<p>Baz</p>
<h2>Quux</h2>
<p>Quux quux</p>
In my JS i already have all h2 elements in a jQuery object:
var $headings = $('h2');
Now i need to find which of those headings has the highlighted class.
So for the above structure the third heading is highlighted, so i expect to receive the answer 2 (JS counts from zero).
I've managed to solve this task with:
function foo($jQueryObject) {
var number;
$jQueryObject.each( function(index, element) {
if ($(element).hasClass('highlighted')) {
number = index;
return false;
}
});
return number;
}
Demo: http://jsbin.com/acaGeJi/1/
But i'm sure there's a more elegant way, something like $headings.index('.highlighted');. Can you please suggest it?
You can use the map method to get the index:
var index = $jQueryObject.map(function(i, e){
return e.hasClass('highlighted') ? i : null;
})[0];
You can also use the index method, but then you have to get the element to look for first, so that means that you look for it twice:
var index = $jQueryObject.index($jQueryObject.filter('.highlighted'));
You can use the $.index function
var search = $( ".highlighted" );
alert( "Index: " + $( "h2" ).index( search ) );
This works for me:
$('.highlighted').index('h2');
jsfiddle demo

How to search Text from Page in jquery [duplicate]

Say a web page has a string such as "I am a simple string" that I want to find. How would I go about this using JQuery?
jQuery has the contains method. Here's a snippet for you:
<script type="text/javascript">
$(function() {
var foundin = $('*:contains("I am a simple string")');
});
</script>
The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/
One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')
Normally jQuery selectors do not search within the "text nodes" in the DOM. However if you use the .contents() function, text nodes will be included, then you can use the nodeType property to filter only the text nodes, and the nodeValue property to search the text string.
$('*', 'body')
.andSelf()
.contents()
.filter(function(){
return this.nodeType === 3;
})
.filter(function(){
// Only match when contains 'simple string' anywhere in the text
return this.nodeValue.indexOf('simple string') != -1;
})
.each(function(){
// Do something with this.nodeValue
});
This will select just the leaf elements that contain "I am a simple string".
$('*:contains("I am a simple string")').each(function(){
if($(this).children().length < 1)
$(this).css("border","solid 2px red") });
Paste the following into the address bar to test it.
javascript: $('*:contains("I am a simple string")').each(function(){ if($(this).children().length < 1) $(this).css("border","solid 2px red") }); return false;
If you want to grab just "I am a simple string". First wrap the text in an element like so.
$('*:contains("I am a simple string")').each(function(){
if($(this).children().length < 1)
$(this).html(
$(this).text().replace(
/"I am a simple string"/
,'<span containsStringImLookingFor="true">"I am a simple string"</span>'
)
)
});
and then do this.
$('*[containsStringImLookingFor]').css("border","solid 2px red");
If you just want the node closest to the text you're searching for, you could use this:
$('*:contains("my text"):last');
This will even work if your HTML looks like this:
<p> blah blah <strong>my <em>text</em></strong></p>
Using the above selector will find the <strong> tag, since that's the last tag which contains that entire string.
Take a look at highlight (jQuery plugin).
Just adding to Tony Miller's answer as this got me 90% towards what I was looking for but still didn't work. Adding .length > 0; to the end of his code got my script working.
$(function() {
var foundin = $('*:contains("I am a simple string")').length > 0;
});
this function should work. basically does a recursive lookup till we get a distinct list of leaf nodes.
function distinctNodes(search, element) {
var d, e, ef;
e = [];
ef = [];
if (element) {
d = $(":contains(\""+ search + "\"):not(script)", element);
}
else {
d = $(":contains(\""+ search + "\"):not(script)");
}
if (d.length == 1) {
e.push(d[0]);
}
else {
d.each(function () {
var i, r = distinctNodes(search, this);
if (r.length === 0) {
e.push(this);
}
else {
for (i = 0; i < r.length; ++i) {
e.push(r[i]);
}
}
});
}
$.each(e, function () {
for (var i = 0; i < ef.length; ++i) {
if (this === ef[i]) return;
}
ef.push(this);
});
return ef;
}

How to remove duplicated content/value with jQuery

So, i have span element where i appending some content - sometimes this content is duplicated. How to remove this one value which is duplicate of another ...
This is how looks like my output html:
<span class="some_class">
"value01"
"value01"
"value02"
"value03"
"value03"
</span>
I can't add any function because i have no idea how to do this, can u help me?
If these values are being added by JS code, then You can make sth like this:
http://jsfiddle.net/Sahadar/Nzs52/5/
You just have to make object which will store all strings placed inside this span, then just before insertion check if this inserted string is already in store object.
function(event) {
var textareaValue = textarea.value();
if(insertedTexts[textareaValue]) {
event.preventDefault();
textarea.value('');
} else {
insertedTexts[textareaValue] = true;
someSpan.append("\""+textareaValue+"\"");
}
}
If these values are already inside span, use function as follows:
var someSpan = $('.some_class');
var insertedTexts = [];
var result = someSpan.text().match(/"\w+(?=\")/gm);
result = result.map(function(value) {
return value.substring(1,value.length);
});
result.forEach(function(value) {
if(insertedTexts.indexOf(value) === -1) {
insertedTexts.push(value);
}
});
var newSpanText = "\""+insertedTexts.join('""')+"\"";
someSpan.text(newSpanText);
console.info(result, insertedTexts);
It's rebuilding span text (trimming etc.) but main functinality is preserved.
jsFiddle working copy:
http://jsfiddle.net/Sahadar/kKNXG/6/
Create an array variable
var vals = [];
which keeps track of the items. Then, in your function that appends items to the span check:
if (vals.indexOf("Mynewvalue") > -1) {
// Add to the span...
}

javascript: Select a class with the right content

i`m working on a Greasmonkey Script, no i want to know how i can test a class for its content.
For example:
<div class="same">Some content</div>
<div class="same">Other content</div>
<div class="same">evenmorecontent</div>
<div class="same">yesthisisalsocontent</div>
<div class="same">youmaynotizedthat</div>
<div class="same">thecontentisdifferent</div>
<div class="same">the cake is yellow</div>
Now i create a array with this classes
var arr = document.getElementsByClassName('same');
Now i want to get the position of "evenmorecontent" in the Array! How do i do this?
If you wanted to use jQuery, you could do this in one line with the contains selector.
In straght JS you need to loop through the array:
var pos = -1;
for(var x=0;x<arr.length;arr++) {
if(arr[x].innerHTML.indexOf('evenmorecontent')>-1) {
pos = x;
}
}
If it occurs more than once, this will return the last position. It will return -1 if not found.
Try not to mix vanilla JS and jQuery while doing this. The following function returns the position of the first occurrence of the text:
var getTextPosition = function (selector, text) {
var pos = -1;
$(selector).each(function(index) {
if($(this).text() === text) {
pos = index;
return false;
}
});
return pos;
};
Example usage:
getTextPosition(".same", "evenmorecontent");
This isn't possible with just one selector. You'll have to loop:
var sameEl = (function() {
var sameArr = document.getElementsByClassName('same');
for (index in sameArr) {
if (sameArr[index].innerHTML === 'evenmorecontent') {
return sameArr[index];
}
}
})();

How to select first class in a list of class definition for an element

I have these elements :
<div id="contentoDinamico">
<div id="item_box_3777" class="index0 itemContenutoDinamico attivo">
<div id="item_box_3792" class="index4 itemContenutoDinamico">
</div>
and this function :
$("#contentoDinamico div").attr('class', function(i, e) {
a.push(e);
});
but I'd like to push only first class for each div child;
so, in the example, index0 and index4, not index0 itemContenutoDinamico attivo and index4 itemContenutoDinamico.
How can I do this?
HTML5 compatible browsers add a classList property to elements which you can index directly. Alternatively you'd have to split the class value by space characters:
$("#contentoDinamico div").each(function(i, e) {
if ('classList' in this) {
a.push(this.classList[0]);
} else {
var cn = this.className;
var ca = cn.split(' ');
a.push(c[0]);
}
}
The space splitting version might break if you have leading spaces in your class attribute.
Split the class that you return by a space, and then there you have it:
.split(/\s/)

Categories

Resources