jquery function works after single space in quotes - javascript

I am learning jQuery and new to it. I was trying to run some code but it was not running and then I found that I just need to give one space before ending double commas/quotes "
$("div:not([id=header]) " + strWhichTag).each(function(){
//some function
});
Now the question is that why do we need to give space after id=header]) if I remove that space and use this code, it doesn't work, the code below doesn't work but Why
$("div:not([id=header])" + strWhichTag).each(function(){
//some function
});
CHANGES------------------------
strWhichTag is basically h3 but it is not child to #header
Second thing I need to know is this
var oList = $("<ul id='bookmarksList'>");
here can I use single quotes and double quotes alternatively or I need to keep the same level like using double quotes and use sigle quotes inside them
I am learning it so any help will be appriciated

First question
The jQuery's argument is a CSS selector.
The space means that you are selecting a child of div:not([id=header]);
"div:not([id=header]) div#foo"
is not the same as
"div:not([id=header])div#foo"
Second question:
The "hierarchy" of quotes doesn't matter, "text'foo'dd" is OK, just as 'text"foo"dd'.
It's up to your taste, but usually using single quotes outside is more practical, since you can have the double ones, used most of the time, in the string.

Lets say
var strWhichTag = 'span';
$("div:not([id=header])" + strWhichTag)
evaluates to $("div:not([id=header])span") // No tag where div and span are equivalent
But if the same is $("div:not([id=header]) span") .. It will try to find all the spans inside the div tag which does not have given id

I dont know what strWhichTag but let assume it is a string like .class
without space, you arent looking a div that is not #header and with the class class.
<div class='class'></div>
This would be ok.
With a space, you are looking for an element with class class inside a div not #header.
<div><img class='class' /></div>
Here, it would select the img.

Related

Target/style an element’s attributes with JavaScript

I'm attempting to change the style of the div element below using JavaScript, but by using its attribute as the selector instead of the class:
<div class="radio-wrapper" data-option-method="Option-A">
For example, I'm able to achieve the desired effect with the following CSS:
.radio-wrapper[data-option-method="Option-A"] { display: none; }
But I'm not having any luck when I attempt the same in the JS:
document.getElementsByClassName(".radio-wrapper[data-option-method="Option-A"]").style.display = "none";
I'm sure this is a fairly simple one, but I'm struggling to research a clear answer, greatly appreciate any suggestions!
First of all, you have a clear syntax error. Your browser console is undoubtedly pointing this out to you. Always check the console for errors.
Since your string contains double-quotes, use single-quotes for the string itself:
'.radio-wrapper[data-option-method="Option-A"]'
Aside from that, document.getElementsByClassName is the wrong function to use here. What you have isn't a class name, it's a more complex selector. document.querySelector can find the element based on that:
document.querySelector('.radio-wrapper[data-option-method="Option-A"]').style.display = "none";
Alternatively, if there are multiple matching elements and you want to target all of them, use querySelectorAll and iterate over the results:
let elements = document.querySelectorAll('.radio-wrapper[data-option-method="Option-A"]');
for (let el of elements) {
el.style.display = "none";
}
The problem is that isn't the class name. ([data-option-method="Option-A"] is an attribute)
Try it with:
document.querySelector('.radio-wrapper[data-option-method="Option-A"]')
If you want to select multiple, use querySelectorAll but bare in mind that returns an array.
Also watch out for the `, ", and ' in strings, either escape them with a " or combine them as I did.

Jquery put elements in div

You need to put items in a div - <div style = 'flex-direction: column;'>.
Div needs to be created after p withid = "billing_city_field"
and closes after the p withid = "apartment_field".
Tried to do it with this function:
jQuery (document) .ready (function ($) {
$ ("# billing_city_field"). after ("<div style = 'flex-direction: column;'>");
$ ("# apartment_field"). after ("</ div");
});
But the div immediately closes. What should I do?
The issue is because you cannot append start/end tags separately. The DOM works with elements as a whole, so you need to create the entire div element in a single operation.
Given the description of your goal it looks like you're trying to wrap the existing content in a new div. As such you can use nextUntil() (assuming the target elements are siblings) and then wrapAll(). Try this:
jQuery($ => {
let $contents = $("#billing_city_field").nextUntil('#apartment_field').add('#apartment_field');
$contents.wrapAll('<div class="column" />');
});
Note the use of a class attribute in the above example, instead of applying inline style rules.
Question is not super clear but from what I can tell.
I think you have small misunderstanding what .after does with jQuery. After in this case is "structural" and not "time" related. If you check jQuery docs (https://api.jquery.com/after/) for this you can see basically what you need to do.
Simplest way to do this, if these things needs to created and don't exist already on body for example.
$(function(){
var p = $("<p id='apartment_field'>Paragraph test</p>");
$("body").append("<div id='billing_city_field' style='flex-direction: column;'></div>");
$("#billing_city_field").html(p);
});
I've added Paragraph test so result is visible easier.
And one more thing, not sure if it's error with copy/paste but make sure that # and id don't have space in-between like this.
$("#billing_city_field")
$("#apartment_field")
Edit: Looking at the comments maybe something like this, if they exist already? You should clarify the question more.
$("#billing_city_field").append($("#apartment_field").detach());

space in javascript

I have a little problem. I have a code with a form input, but the form input class is named
text-input small-input
I can't change this because of CSS issues and this is the problem, because when I add the space in my javascript code, my code doesn't work anymore
Javascript code
$(document).ready(function() {
$('.text-input*small-input').keyup(function() {
var search_term = $(this) .val();
$.post('search.php', {search_term:search_term}, function(data) {
$('.result').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('.text-input*small-input') .val(result_value);
$('.result').html(' ');
});
});
});
});
So at the * sign, there needs to be a space. Any way to solve this? Thanks!
you do not want a space, you want nothing there. just .text-input.small-input to tell the selector engine to look for an element with both of those classes.
here is a very good article explaining multiple part selectors.
You had two issues. You don't want a space and you do want a dot on the second class.
To specify a requirement of two classes on the same object in a CSS selector, you put no space between the two class names:
$('.text-input.small-input') // find single object with both classes on it
With a space, it does something different:
$('.text-input .small-input') // find .small-input with ancestor .text-input
When you put a space between them, that creates a selector that finds an object that matches .text-input and a child that matches .small-input and the matched object is the child. No space between them means both classes must be on the same object. This is how CSS specifications work and isn't jQuery-specific.
FYI, what you were trying to do with this:
$('.text-input small-input') // find <small-input> with ancestor that is .text-input
was trying to find an object with a tag of <small-input> that had an ancesotr of .text-input because you put no special character in front of small-input so it was interpreted as a tag name.

How to add class to words starting with a hashtag in jQuery?

So let's say I have a string in jQuery that looks like
result.text = "I tweeted something #one #two #three";
Is there a way to wrap all the words starting with a hashtag with a span class called "tweet-hash" ?
You'll probably want to use some Regex to find the symbol/word combination, and replace it and wrap it with a style tag and a CSS class. CSS unfortunately doesn't have a selector for values like that.
$("#phrase").html($("#phrase").html().replace(/#([^ ]+)/, "<span class='hashtag'>$1</span>")
It's worth noting that the example above will only replace the first hashtag it finds. If you add a g global to the regex expression, it will target all instances that match the expression:
$("#phrase").html($("#phrase").html().replace(/#([^ ]+)/g, "<span class='hashtag'>$1</span>");
I've thrown up an example on jsFiddle so you can see the difference: http://jsfiddle.net/c26r9/

In JQuery, how do I remove a comma after removing an element?

var body = 'Alex, Jason, Kate, how are you?";
I want to use JQuery to remove the anchor element from body, and then also remove the comma after the anchor, if there is any. Note: to make it easy, the comma will always be after the anchor with no other characters in between.
I'm assuming (to maintain grammatical consistency) that you also want to remove the contents of the anchor.
Firstly, use a regexp to get rid of the comma:
var body = 'Alex, Jason, Kate, how are you?';
body = body.replace(/(<\/a>),/g, '$1')
Then to allow jQuery to work on the string you need to enclose it in an element:
body = '<div>' + body + '</div>'
Then you can actually remove the element
body = $(body).children('a').remove().end().html();
NB: the code above will remove all <a> elements within the text, but leave other HTML elements therein untouched.
If you're thinking of removing elements like that then it would be better to encase them in something to "mark them off" as it were. You're saying that the name "Jason" is tied to the superseding comma, so mark them off. e.g.:
var body = 'Alex, <span class="name">Jason,</span> Kate, how are you?";
Then to remove in jquery you can do something like:
$('a').click(function(){ $(this).closest('.name').remove(); });
This is the best way to do it, mainly because you have control over what is important to which text elements. A regex, or some way of removing the next single character will work in your example, however what happens if you want to extend your sentence, eg: 'Alex, Jason (the farmer's son), Kate, how are you?'.

Categories

Resources