Finding a span where the class contains a text string JQuery - javascript

I am using JQuery to find a span element that contains a string of text in the class, but could also contain other text.
var not_breaks = element.filter("span.this_text");
This works for spans where class="this_text" but not class="this_text_and_more_text" - I need to search for both.

In that case you could use the Attribute Contains selector:
var not_breaks = element.filter("span[class*='this_text']");
You could also use the Attribute Starts With selector, but note that this is only guaranteed to work if the element has a single class on it:
var not_breaks = element.filter("span[class^='this_text']");

We can get all the span class with the name by using a hasclass, Will this help you
var pare=$('span');
$( pare ).each(function() {
if($(this).hasClass('httext')){
alert($(this).html())
}
});

I need to search for both
I'd do that with a selector group:
var not_breaks = element.filter("span.this_text, span.this_text_and_more_text");
// first ---^ comma ---^ ^---- second
That will retain elements matching either selector in the group.
Example:
var element = $("span");
var not_breaks = element.filter("span.this_text, span.this_text_and_more_text");
not_breaks.css("color", "green");
<div><span>Not a match</span></div>
<div><span class="this_text">this_text</span></div>
<div><span>Not a match</span></div>
<div><span class="this_text_and_more_text">this_text_and_more_text</span></div>
<div><span>Not a match</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can use regex to retrieve the any sequence as you need.
var regex = new RegExp("this_txt");
var elem = $("span").filter(function () {
return regex.test($(this).attr('class'));
});
console.log(elem.length);
regex.test function will only return true if the sequence exists.
here's the fiddle
https://jsfiddle.net/yt1cr2zb/

Related

How to check if data-attribute does not contain a string with :contains in jQuery

Is it possible to apply :not(:contains()) selector to data-attribute? Here is what I have in HTML:
<input id="keyword">
<button id="find1">Find - 1</button>
<button id="find2">Find - 2</button>
<div class="list_item" data-stringtofind="abc def">abc def</div>
<div class="list_item" data-stringtofind="ghi jkl">ghi jkl</div>
<div class="list_item" data-stringtofind="mno prs">mno prs</div>
What I'd like to do is to filter it on click based on what is inside of data-stringtofind attribute. I'm trying with this code, but it's not working.
$('#find1').on('click', function () {
var findthis = $('#keyword').val();
console.log(findthis);
$( ".list_item.data('stringtofind'):not(:contains("+ findthis +"))").hide();
console.log(".list_item.data('stringtofind')");
});
Here is what the console outputs:
Error: Syntax error, unrecognized expression: .list_item.data('stringtofind'):not(:contains(abc))
Am I doing some simple mistake or this just isn't possible to do with :not:contains?
This code works, but it searches inside of the div, not inside of the data-stringtofind attribute.
$('#find2').on('click', function () {
var findthis = $('#keyword').val();
console.log(findthis);
$( ".list_item:not(:contains("+ findthis +"))").hide();
console.log(".list_item.data('stringtofind')");
});
Here is a fiddle: https://jsfiddle.net/mk7yr62k/2/
:contains isn't related to attributes at all. You want an attribute substring selector:
$( ".list_item:not([data-stringtofind*='" + findthis + "'])").hide();
[data-stringtofind*='xxx'] means "xxx anywhere in the data-stringtofind attribute." And of course, :not negates it.
Here's an example:
var p = $("<p>").text("Waiting briefly...").appendTo(document.body);
setTimeout(function() {
var findthis = "abc";
$( ".list_item:not([data-stringtofind*='" + findthis + "'])").hide();
p.text("Hid the ones not matching 'abc'");
}, 500);
<div class="list_item" data-stringtofind="abc def">abc def</div>
<div class="list_item" data-stringtofind="ghi jkl">ghi jkl</div>
<div class="list_item" data-stringtofind="mno prs">mno prs</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
:contains is used to find an element by the text it contains, not the contents of an attribute, and hence is not suitable for what you require.
An alternative would be the attribute contains selector, but this will match on spaces too - ie. bc de would hit your first element.
To fix this you could use filter() and convert the data attribute of each element to an array and use indexOf() to find a match. Try this:
$('#find1').on('click', function () {
var findthis = $('#keyword').val();
$('.list_item').filter(function() {
var arr = $(this).data('stringtofind').split(' ');
return arr.indexOf(findthis) != -1;
});
});
Working example
Try this, it searches for your string in each .list_item and hides it if there's no match.
$('#find1').on('click', function () {
var findthis = $('#keyword').val();
$(".list_item").each(function() {
if ($(this).data('stringtofind').indexOf(findthis) == -1)
$(this).hide();
});
});

Case insensitive jQuery attribute selector

I am doing the following using attribute contains selector $('[attribute*=value]')
<input name="man-news">
<input name="milkMan">
<script>
$( "input[name*='man']").css("background-color:black");
</script>
This works for the 1st input but not the second input as "Man" has a capital "M"
How can I make $( "input[name*='man']") an case insensitive selector?
The simplest way to do this is to add a case insensitivity flag 'i' inside the regex part of the selector:
So instead of
$( "input[name*='man']")
You could do
$( "input[name*='man' i]")
JS fiddle: https://jsfiddle.net/uoxvwxd1/3/
You can always use .filter():
var mans = $('input').filter(function() {
return $(this).attr('name').toLowerCase().indexOf('man') > -1;
});
mans.css('background-color', 'black');
The key part here is toLowerCase() which lowercases the name attribute, allowing you to test it for containing man.
var control = $('input').filter(function() {
return /*REGEX_VALUE*/i.test($(this).attr('id'));
});
*REGEX_VALUE* - the value you want to find
I ended up using regex to validate whether the attribute 'ID' satisfy... regex is much more flexible if you want to find a certain matching value or values, case sensitive or insensitive or a certain range of values...
I was just able to ignore jQuery's case sensitivity altogether to achieve what I want using below code,
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
You can use this link to find code based on your jQuery versions,
https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/
Also there is an article where it does to many good things with jQuery: http://www.ultechspot.com/jquery/using-jquery-search-html-text-and-show-or-hide-accordingly
This works for me using jQuery and if i'm adding item to a table
// check if item already exists in table
var inputValue = $('#input').val(); // input
var checkitem = $('#exampleTable td.value div.editable').filter(function() {
//check each table's editable div matches the input value in lowercase
if ($(this).text().toLowerCase() === inputValue.toLowerCase()) {
itemexists = true;
}
});
if (itemexists) {
alert("item exists in the table");
return;
}

how to get the value of an attribute using jquery

I need to get the attributes values of an element.
My code is as follows:
var vid=$('div.selected a');
var dataid=$(vid).data('vid');
var dataalid=$(vid).data('alid');
And HTML
<div class="vblock" id="selected">
<a class="video" data-alid="4" data-vid="4" href="resources/videos/xyz4.mp4">
I need to get the value of data-alid and data-vid of <a> tag. Please anyone help me....
You are almost there with what you have, but you've made a simple mistake. Your markup shows that the div has an ID of "selected", not a class, so you need to use an ID selector:
var vid=$('#selected a');
Notice that I've removed the div from the selector. That's because ID values must be unique within a document and there is therefore no need to qualify them.
Also, note that since $ will return a jQuery object, there is no need to pass vid to it again, which will be slower:
var dataid = vid.data('vid');
var dataalid = vid.data('alid');
trythis
var vid=$('div#selected a');
var dataid=$(vid).attr('data-vid');
var dataalid=$(vid).attr('data-alid');
you have a wrong selector for id.. and you don't need double $(...)
try this
var vid=$('div#selected a');
--------------^--- here this is id and not class
var dataid=vid.data('vid');
-----------^-- here
var dataalid=vid.data('alid');
Try this way, instead of '.' you have to use '#' because you are referring to an id and use .attr() to refer to your specific attribute
$(document).ready(function() {
var vid=$('div#selected a');
var dataalid = vid.attr('data-alid');
var datavid = vid.attr('data-vid');
});

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

JS Prototype get element by class?

I got the following code and I'm trying to make it match on a class instead of on an id:
Html:
<div id='testdiv'>
<div class="lol">
[First Title|<a class="external" href="http://test.com">http://test.com</a>]
Another line
[Second Title|<a class="external" href="http://test.com">http://test.com</a>]
More text
[Third Title|<a class="external" href="http://test.com">http://test.com</a>]
</div>
</div>
Javascript:
var textContainer = document.getElementById("testdiv");
var linkText = textContainer.innerHTML;
var pattern = /\[([^|]+)\|([^>]+.?)[^<]*(<\/a>)\]/g;
var result = linkText.replace(pattern, "$2$1$3");
textContainer.innerHTML = result;
Full example: http://jsfiddle.net/JFC72/17/
How can I make it match on "myclass" instead?
Thanks!
Use a css selector in prototype.
var textContainer = $$('div.myclass')[0];
jsfiddle
I think you need the $$ method. It selects DOM elements that match a CSS selector strict. In this case you want
var elements = $$('.myclass');
It returns a list of all matching elements in document order. You can access them by index or operating on all of them with things like each
http://www.prototypejs.org/api/utility
This is what Prototype is about. getElementById is oooold
Here is a working example of how you would use each in Prototype to loop through all elements with a class of order-cc-charged.
var order_cc_charged = 0;
$$('order-cc-charged').each(function (elem) {
order_cc_charged += parseFloat($('order-cc-charged').innerHTML);
});

Categories

Resources