How to execute partial find on dynamic HTML5 data descriptor? - javascript

I have a series of images tagged with HTML5 data descriptor "data-type2=[x]" where x is a number of different elements.
e.g.
<img data-type2="pants" class="element" src="#>
I am trying to pass that data field into a jquery function that finds classes in another div (<div class="outfit-list") that has child divs tagged with classes such as:
<div class="pants-001">
<div class="pants-002">
<div class="shoes-001">
etc.
Here is where I am stumped: how do I write a jquery function that accesses data type2 from the item I click (e.g. data-type2="pants"), finds all other divs under .outfit-list with classes that have, for example, "pants" in their class name "pants-002", and hide them? The function I have below does not work - I suspect that's because it's looking for the full name and not partial.
How do I make it perform a partial search to locate the classes that contain the term from data-type2?
<script type="text/javascript">
$(document).ready(function(){
$('.thumbslist .element').click(function(){
$('.outfit-list').find('.'+$(this).data('type2')).hide();
});
});
</script>

You can use the attribute contains selector, [attribute*="value"].
$('.outfit-list').find('[class*="' + $(this).data('type2') + '"]').hide();

You can use the starts with selector. Something like
$(".thumbslist .element").click(function() {
var type2 = $(this).data("type2");
$(".outfit-list").find("div[class^=" + type2 + "]").hide();
});

This plugin adds support for data selectors: http://plugins.jquery.com/project/dataSelector

First of all, the jQuery .data() method is amazing: http://api.jquery.com/data/
You could do:
$("#img1").data('type', 'pants')
// Or whatever else you need to attach data to. You can do this dynamically too!
t = $("#img1").data('type')
// Recall that data at some point
$("div").each(function() {
pat = new RegExp(t)
if ($(this).attr('class').search(pat) !== -1) {
$(this).hide()
}
});
Or even better in Coffeescript
t = $("#img1").data 'type'
$("div").each ->
if ($(#).attr('class').search new RegExp t) isnt -1 then $(#).hide()

May be with something like in this other question
jQuery selector regular expressions

You could just grab the value of the attribute then use it in an attribute selector: http://jsfiddle.net/n73fC/1/

Related

select a string after a substring in an element's class name

I have an element that contains an input text, to get the input text I'm using the jQuery method find.
The input text has a class name like this page-id-x with the x is variable, so I want to select that number after the substring page-id, and this is what I tried :
var id = ui.item.find('input').attr('class').split(/\s+/).filter(function(s){
return s.includes('page-id-');
})[0].split('-')[2];
console.log(id);
I think this code is too complicated, but I couldn't figure out some other way to do it.
If someone knows a better way, I'll be thankful.
Thanks in advance.
I'm going to assume the x part of page-id-x, not the id part, is what varies (since that's what your code assumes).
Another way to do it is with a regular expression, but I'm not sure I'd call it simpler:
var id = ui.item
.find('input')
.attr('class')
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
Example:
var ui = {
item: $("#item")
};
var id = ui.item
.find('input')
.attr("class")
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
console.log(id);
<div id="item">
<input class="foo page-id-23 bar">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above makes the same assumptions your current code does, which are:
The first input in ui.item is the one you want
It will have the relevant class name
I assume those are okay, as your question is asking for an alternative, suggesting what you have is working.
As you're using jQuery, take a look at this: https://api.jquery.com/category/selectors/attribute-selectors/
For your case, you can use $('[class^="page-id-"'). These types of selectors (listed on the link above) actually work in CSS, too. (At least most should, if not all.)
To get the number after page-id-, my suggestion would be to store that number in some other HTML attribute, like data-pageID="1" or the like.
So you could have:
<div id="page-id-3" data-pageID="3">CONTENT</div>
Then, when you have the DOM element using $('[class^="page-id-"'), you can access that number with .attr('data-pageID').val().
If you can control the HTML markup, instead of using class names, you can use data attributes instead. For example, instead of:
<input class="page-id-1">
You can use:
<input data-page-id="1">
Then jQuery can find this element effortlessly:
$('[data-page-id]').attr('data-page-id')
You can find your element using the *= selector.
let elem = document.querySelector('[class*=page-id-]')
Once you have the element, you can parse the id out:
let [base, id] = elem.className.match(/page-id-(\d+)/)
console.log('page id: %s', id);

jQuery Find and Replace all instances of part of a classname

I have several div's with a classname that looks like this:
class="col-md-4"
some have:
class="col-md-12"
What I want to do is to search for whatever the number at the end of the class is and replace all of them to:
class="col-md-6"
How can I do this using jQuery?
You can use special selectors in jQuery:
^= starts with ...
*= contains ...
Or use a combination of both selectors if you don't get them all.
var cols = $('[class^="col-md-"]');
Then to remove all classes with a wildcard
cols.removeClass(function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
});
Then add the class you want:
cols.addClass('col-md-6');
Try to remove the class and add the new one:
$(".col-md-4").removeClass("col-md-4").addClass("col-md-6");
$(".col-md-12").removeClass("col-md-12").addClass("col-md-6");
you can use "contains" selector like this
$("[class*='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-6");
removeClass function based on this answer
$("[class*='col-md-']")
will find any element with a class that contains col-md-.
The removeClass function will than remove it. And finally col-md-6 will be added.
EDIT
changed [class^='col-md-'] to [class*='col-md-'] in case class attribute has another class before col-md-. Thank you #dfsq for pointing this out
This should also work:
$('[class*=col-md]').removeClass('col-md-4 col-md-12').addClass('col-md-6');
You could do it with simple javascript if all of those elements were inside a main div.
For example:
var arr_divs = document.getElementById('main_div').getElementsByTagName('div');
for(var i = 0; i < arr_divs.length; i++){
if(arr_divs.item(i).className == 'col-md-12' || arr_divs.item(i).className == 'col-md-4'){
arr_divs.item(i).className = 'col-md-6';
}
}
This may not be the most efficient way of doing what you want but, it keeps it simple. Here's a working fiddle: https://jsfiddle.net/Lns1ob5q/
$("[class^=col-md-]").attr("class", "col-md-6");
The above selects all elements with a class containing col-md- ([class^=col-md-]) and replaces the class, regardless of what number immediately follows, with col-md-6.
The reason I say it's not efficient is becuase jQuery will initially pick up elements that already have a class of col-md-6 and replace their class with the same one... But hey, it works!

javascript variable for jquery script

I dont know Javascript at all, so sorry for asking a question like this...
This is what I have:
$(document).ready(function(){$("#more0").click(function(){$("#update0").slideToggle("normal");});});
$(document).ready(function(){$("#more1").click(function(){$("#update1").slideToggle("normal");});});
$(document).ready(function(){$("#more2").click(function(){$("#update2").slideToggle("normal");});});
$(document).ready(function(){$("#more3").click(function(){$("#update3").slideToggle("normal");});});
$(document).ready(function(){$("#more4").click(function(){$("#update4").slideToggle("normal");});});
$(document).ready(function(){$("#more5").click(function(){$("#update5").slideToggle("normal");});});
$(document).ready(function(){$("#more6").click(function(){$("#update6").slideToggle("normal");});});
$(document).ready(function(){$("#more7").click(function(){$("#update7").slideToggle("normal");});});
$(document).ready(function(){$("#more8").click(function(){$("#update8").slideToggle("normal");});});
$(document).ready(function(){$("#more9").click(function(){$("#update9").slideToggle("normal");});});
$(document).ready(function(){$("#more10").click(function(){$("#update10").slideToggle("normal");});});
And So On.. Until #more30 and #update30...
So... Right now, my pages has 30 lines :)
Is there a way to do it less complicated?
Thanks!
Use attribute selector ^= . The [attribute^=value] selector is used to select elements whose attribute value begins with a specified value.
$(document).ready(function(){
$("[id^='more']").click(function(){
$("#update" + $(this).attr('id').slice(4)).slideToggle("normal");
});
});
Try to use attribute starts with selector to select all the elements having id starts with more , then extract the numerical value from it using the regular expression and concatenate it with update to form the required element's id and proceed,
$(document).ready(function(){
$("[id^='more']").click(function(){
var index = $(this).attr('id').match(/\d+/)[0];
$("#update" + index).slideToggle("normal");
});
});
use attribute start with selector
$(document).ready(function(){
$("[id^='more']").click(function(){
$("[id^='update']").slideToggle("normal");
});
});
//select all elements that contain 'more' in their id attribute.
$('[id^=more]').click(function(){
//get the actual full id of the clicked element.
var thisId = $(this).attr("id");
//get the last 2 characters (the number) from the clicked elem id
var elemNo= thisId.substr(thisId.length-2);
//check if last two chars are actually a number
if(parseInt(elemNo))
{
var updateId = "#update"+elemNo;//combine the "#update" id name with number e.g.5
}
else
{
//if not, then take only the last char
elemNo= thisId.substr(thisId.length-1);
var updateId = "#update"+elemNo;
}
//now use the generate id for the slide element and apply toggle.
$(updateId).slideToggle("normal");
});
Well first of all, you could replace the multiple ready event handler registrations with just one, e.g
$(document).ready(
$("#more0").click(function(){$("#update0").slideToggle("normal");});
//...
);
Then, since your buttons/links has pretty much the same functionality, I would recommend merging these into a single click event handler registration as such:
$(document).ready(
$(".generic-js-hook-class").click(function(){
var toggleContainer = $(this).data('toggleContainer');
$(toggleContainer).slideToggle("normal");
});
);
The above solution uses HTML Data Attributes to store information on which element to toggle and requires you to change the corresponding HTML like so:
<div class=".generic-js-hook-class" data-toggle-container="#relatedContainer">Click me</div>
<div id="relatedContainer>Toggle me</div>
I would recommend you to use Custom Data Attributes (data-*). Here You can store which element to toggle in the data attributes which can be fetched and used latter.
JavaScript, In event-handler you can use .data() to fetch those values.
$(document).ready(function () {
$(".more").click(function () {
$($(this).data('slide')).slideToggle("normal");
});
});
HTML
<div class="more" data-slide="#update1">more1</div>
<div class="more" data-slide="#update2">more2</div>
<div id="update1">update1</div>
<div id="update2">update2</div>
DEMO

Using jQuery, how to specify with the `.attr` method, the second of two html classes?

When using jQuery and are using the .attr method as follows:
$(document).ready(function(){
$('.class1').click(function(){
id = $(this).attr('.class2');
});
});
Say I have the following HTML for the above function:
<div class="class1 $class2"></div>
The second class is attributed at runtime, so I have 10 divs, each with class1, but several with class2. Then I wish to use the jQuery function at the top, so that whenever I click on any of the divs, it applies the specific class2 of that div, to the variable ID.
I hope this makes more sense.
Since your class2 comes from your PHP code, you seem to hit the usecase of data-attributes.
With data-attributes you can easily have some extra data (often used for javascript purposes) on your HTML elements without having to use special classes or ids for that.
It works like that:
<span data-hero="batman">I'm a Bat!</span>
Where in your Javascript (using jQuery) you get the value of it by simply doing:
$('span').data('hero');
Refer to the MDN and the jQuery documentation for further information.
Is this what you're trying to do?
$(document).ready(function(){
$('.class1').click(function(){
var id = $(this).attr('class').replace('class1','').trim();
});
});
If you have a multi class tag this mean the HTML code would be like this:
<sometag class="class1 class2">...</sometag>
I think the simplest approach is to do some string operations on the class attribute of the tag:
var class2 = $(selector).attr("class").split(" ")[1];
OR you can write a simple jQuery plugin to do the work for you:
(function($){
$.fn.secondClass = function(){
var c = this.attr("class").split(" ");
if(c.length >= 2)
return c[1];
};
}(jQuery))
Usage: var class2 = $(selector).secondClass();
Hope this helps.

How to get element by both id and class

Is there any alternative solution (in JavaScript) for document.getElementById(); to select a specific element, specifying both the class and id ?
for example I have such a content:
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="2"></div>
And I want to select the corresponding div under the "Question X" link in the function
function showQuestion(id)
{
var thediv = GetByClassAndId("q_content",id); // how to implement this function ?
WriteQuestionIn(thediv); //Ajax
}
Thanks in advance.
you can try document.querySelector()
like document.querySelector(".q_content#2") use the para like css selector..
Since ID is always unique (unless u make a mistake) u have no need to use both class and id to select the element.
Such an approach is not correct, and should be avoided at all cost.
What I suspect is your problem, is that the ID is only a number. Try adding a prefix which is a letter. Do view source to this page to see examples.
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="q1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="q2"></div>
function showQuestion(id)
{
var thediv = document.getElementById("q"+id);
WriteQuestionIn(thediv); //Ajax
}
Actually there is a function $ in jQuery for doing this operation. If you are using any framework, then you should remember there is always a jQuery library available. Else if you are using custom PHP, then add one of them like jQuery or other because they provide lots of types of selectors.
Now here is the code after adding jQuery:
$("#yourid") //basic selector
$("#yourid.yourclass").show()
Use .show() to show the selected element
Use .hide() To hide element

Categories