Select a div ending with some things - javascript

<div id="start_123_end"</div>
<div id = "start_123_ok"</div>
<div id="start_123_error"</div>
<div id = "start_123_notstarted"</div>
I want to select a div which start with "start" and ends with "end " or "ok"
Pseduo Code:
vae selected $("div[id^=__w2][id$=_end || _ok]")
as there can be many elements

You can use .filter()
var selected = $("div[id^=start]").filter("[id$=_ok],[id$=_end]");
DEMO

Use start and end selector with comma
$('div[id ^=start][id $=_ok],div[id ^=start][id $=_end ]')

Instead of rather slow attribute selectors, you can use a filter with a regex:
$('div').filter(function() {
return /^start.+(end|ok)$/.test(this.id);
}).addClass('selected');
Example fiddle

Related

How to get class name of element has specific text using javascript/jquery?

I need a JavaScript or jQuery way of extracting the Class name of DIV element by the text it contains.
Let's illustrate. If I had let's say following code:
<div class="_className">UniqueText</div>
I need to to know how to programmatically do something like this:
getClassNameWhereText("UniqueText");
In this case output should be:
_className
Is there a way to do this?
JQuery :contains selector select element has specific text but it isn't exact. For example
$("div:contains(UniqueText)")
Select both of bottom divs
<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>
You can use .filter() to filter selected element by text.
var className = $("*").filter(function(){
return $(this).text() == "UniqueText";
}).attr("class");
var className = $("*").filter(function(){
return $(this).text() == "UniqueText";
}).attr("class");
console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>
By getting all the div with each function you can search through all the divs and place a condition in which you the value of the div is equal to the particular text that you want to find. Then get the class name by using .attr('class').
$( "div" ).each(function(){
if($(this).text() == "UniqueText"){
var output = $(this).attr('class');
$(".output").html(output);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_classname">UniqueText</div>
<div class="output"></div>
It might be a bit long for a code but it gets the work done nicely. :)
You can use :contains(word)
var className = $( "div:contains('John')" ).attr("class");
console.log(className)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">John Resig</div>
<div class="bar">George Martin</div>
<div class="foo">Malcom John Sinclair</div>
<div class="baz">J. Ohn</div>
You can keep an id for your div, as per your information your text will be unique.
<div id="UniqueText" class="_className">UniqueText</div>
and the js code will be
function getClassNameWhereText(text){
var className = $('#'+text).attr('class');
console.log(className);
}
UPDATE : if you want to using contains
then you can do this,
function getClassNameWhereText(text){
var val = document.getElementById(text).value;
if(text.indexOf(val)>=0){
var className = $('#'+text).attr('class');
console.log(className);
}
}
This should be faster than using jQuery (but a bit more to type):
var xpath = "//div[text()='UniqueText']";
var result = document.evaluate(xpath,
document, null, XPathResult.FIRST_ORDERED_NODE_TYPE);
var node = result.singleNodeValue;
if (node) {
console.log(node.className);
} else {
console.error("Not found!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>
The reason is, browser's CSS selectors don't support :contains selector, and jQuery needs to emulate it by checking every node matching the rest of the selector. Ditto for using .filter. But XPath is done natively by the browser.
You also cannot specify exact match using the jQuery :contains, like here. If substring matching was indeed needed, you can change the XPath:
var xpath = "//div[contains(text(),'UniqueText')]";
XPath is very powerful, but a bit finicky and largely unknown, so I find it is very under-utilised, even when its use would be a perfect fit.

Is it possible to change the class name of a div element

I have something like shown below.
<div class="alert alert-info" style="width:224px">
<strong>Info!</strong> This is a netural alert
</div>
Through javascript or jquery, at certain condition, I want to change the class of that div element from alert alert-info to alert alert-success. Is that possible? And if so, how?
Change class with condition, Use the following sample
$('.alert').click(function(){
if(0==0)//your condition goes here
{
$(this).removeClass('alert-info').addClass('alert-success');
}else{
$(this).removeClass('alert-success').addClass('alert-info');
}
});
you can use:
document.getElementById("myElementId").className = "MyClass";
use space-delimited list to apply multiple classes,if you want to add class here is an example:
document.getElementById("myElementId").className += " MyClass";
var divArray = document.getElementsByClassName("alert-info");
var div = divArray[0];
div.className = "alert alert-success";
With jQuery....
$('.alert').removeClass('alert-info').addClass('alert-success');
.. Unless I'm missing something.

How can I remove content like from an element?

I have a div where the content looks like this:
<div class="container">
<div class="eventSpot bg-blue"></div>
<div class="eventSpot bg-blue"></div>
<div class="eventSpot bg-red"></div>
</div>
The is causing some styling problems so I need to remove it.
How can I remove just that part of the content with jQuery/javascript?
Using jQuery:
var div = $('div.container');
div.html(div.html().replace(/^\s* /m, ''));
I prefer working with nodes instead of html as a string if possible, so I would suggest something like this:
http://jsfiddle.net/p7v89/
$('.container').contents().filter(function() {
return this.nodeType == 3
}).remove();
That will find all text nodes and remove them.
you will get the text without HTML tag and &nbsp etc
This is a solution for HTML tag and &nbsp etc and you can remove and add conditions
convertHtmlToText(passHtmlBlock)
{
str = str.toString();
return str.replace(/<[^>]*(>|$)| |‌|»|«|>/g, ' ');
}
You could alternatively try the .detach() method.
var $data = $('.container > div').detach();
$('.container').empty().html($data);

Siblings with same attribute value

I have a div structure like
<div>
<div class='class1'>contens</div>
<div class='class2'>contens</div>
<div class='class2'>contens</div>
<div class='class2'>contens</div>
<div class='class3'>contens</div>
<div class='class2'>contens</div>
<div class='class1'>contens</div>
</div>
Here I want to write a selector which will select all the div elements with class='class2', they should be adjacent to each other. i.e I should select only index 1,2,3 but not div index 5 since its not adjacent to group.
Please Help here.
You can use the adjacent sibling selector
var elems = $('.class2 + .class2').add( $('.class2 + .class2').prev() )
FIDDLE
or caching the selector (with an argument to a IIFE)
var elems = (function(x) {return x.add( x.prev() )})($('.class2 + .class2'));
FIDDLE
Here is an alternative solution with .filter:
For example:
$('.class2').filter(function() {
return $(this).prev('.class2').add($(this).next('.class2')).length > 0;
});
It filters out the elements that don't have a sibling with class .class2.

How to use jquery to select all elements that have two specific attributes

I have some markup where a lot of id's have an id attribute, as well as innerText. I want to select each of these elements, performing a function on the id.
How do I do that?
Something like this?
$('[id]:not(:empty)').each(function(i, el) {
// do stuff
});
Give them a common class:
HTML
<div id="first" class="all"></div>
<div id="second" class="all"></div>
<div id="third" class="all"></div>
jQuery
$('div.all').each(function(index){
processid(this.id);
});
If you are talking about selecting elements whose id (or some permutation of it) is included in its text then
$('[id]').filter(function(){
return $(this).text().indexOf( this.id ) >= 0; // the this.id should be altered to match the permutation you seek ..
}).css('color','red'); // turn those to red
After you comment to #lonesomeday (at the question comments) here is what to do ..
$('[id]').each(function(){
processid(this.id);
});
First select by a regular ID selector and then loop over that selection by filtering .text() non-empty.
$("[id]").each(function() {
if ($(this).text() != "") {
// do stuff
}
});

Categories

Resources