I have a webpage which contains such code:
<img class="img-qrcode" id="img_123.000.00.01"
src="http://localhost:7777/data/code_img\123.000.00.01.png"
alt="./data/code_img\123.000.00.01.png" style="display:none">
I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:
$("#img_123.000.00.01")
The added screenshot shows that it returns an empty array.
Why does it not find the element with ID ?
Using an attribute selector for id, you don't have to worry about escaping the class selector (.)
let img = $("img[id='img_123.000.00.01']");
console.log(img.attr('src'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123.000.00.01"
src="http://localhost:7777/data/code_img\123.000.00.01.png"
alt="./data/code_img\123.000.00.01.png" style="display:none">
The a . character has special meaning in a selector (it starts a class selector) so you need to escape it. (Remember to escape the slash character in a string literal).
Generally it is easier to just avoid using . chapters in an id.
Find with ^
let img = $("img[id^='img_123']");
console.log(img.attr('src'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123"
src="http://localhost:7777/data/code_img\123.000.00.01.png"
alt="./data/code_img\123.000.00.01.png" style="display:none">
When some special symbols are in the jquery selector, you need to add 『\\』
console.log($("#img_123\\.000\\.00\\.01"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<img class="img-qrcode" id="img_123.000.00.01" src="http://localhost:7777/data/code_img\123.000.00.01.png" alt="./data/code_img\123.000.00.01.png" style="display:none">
</body>
</html>
Since #id.className is a valid selector jQuery assumes it so and tries to find such element. In your case you will have to escape the dot.
Change $("#img_123.000.00.01") to $("#img_123\\.000\\.00\\.01") and it will work.
Official jQuery documentation(https://api.jquery.com/category/selectors/) states it clearly.
To use any of the meta-characters ( such as
!"#$%&'()*+,./:;<=>?#[\]^{|}~` ) as a literal part of a name, it
must be escaped with with two backslashes
Related
I need to add a closing image tag. Current html:
<img class="logoEmail" src="/images/logoPDF.png">
What I want:
<img class="logoEmail" src="/images/logoPDF.png"/>
How can I do that?
myInput ='<img class="example1" src="/images/example1.png">';
myInput += '<img class="example2" src="/images/example2.png"/>';
result = myInput.replace(/(<img("[^"]*"|[^\/">])*)>/gi, "$1/>");
Explanation of the regex:
<img The start
"[^"]*" A string inside the tag. May contain the / character.
[^\/">] Anything else (not a string, not a / and not the end of the tag)
> The end of an IMG tag
This will only match unfinished tags, and will replace it by the whole thing, plus a />
As I said before this is NOT bulletproof, probably there is no regex that would work 100%.
You could try this regex also,
result = myInput.replace(/^([^\.]*\.[^>]*)(.*)$/g, "$1/$2");
DEMO
It captures all the characters upto a literal dot and stored it into a group. Then it again captures characters upto > and stored into another group. Add a / in between the captured groups in the replacement part will give you the desired output.
It can be as easy as this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo Replace IMG tags w/ regex</title>
<script type="text/javascript">
window.onload = function() {
document.body.innerHTML = document.body.innerHTML.replace(/(<img[^>]+)/g, "$1 /");
}
</script>
</head>
<body>
<p>Some text.</p>
<img src="images/logoPhone.jpg">
<br>
<img src="images/logoMail.png">
<p>Some more text.</p>
</body>
</html>
.
Explanation:
<img: match must start with this.
[^>]: after the starting match, the next character may be anything but >.
+: one or more occurances.
g: apply globally, do not return on the first match.
$1: as in the first capture group (= stuff between first set of parentheses).
.
Be aware that Firebug never shows closing slashes, regardless of doctype. But you can see the regex script in action here: http://regex101.com/r/zS2zO1.
I want to make letters like 'å ä ö' visible. I need to replace these letters with ascii code, I guess.
I have tried jquery and javascript, but it did not work. Look at the following code please:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
jQuery("#body").html(
jQuery("#body").html().replace('ä', 'å')
);
document.body.innerHTML = document.body.innerHTML.replace(/ä/g, 'å');
</script>
</head>
<body id="body">
<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item active" href="index.php">Inlägg</a>
</nav>
</div>
</div>
You can achieve what you want using one of the three methods below.
codepen
JQuery
// using a regex on the first parameter of replace,
// picks all the 'ä' instead of the first one
var replaced = $("body").html().replace(/ä/g,'å');
$("body").html(replaced);
JavaScript
// using a regex on the first parameter of replace,
// picks all the 'ä' instead of the first one
document.body.innerHTML = document.body.innerHTML.replace(/ä/g, 'å');
Better Solution
A better alternative to the two previous code sample is to convert your file to the right encoding. In order to do that, make sure you this snippet in the head of you HTML document.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
If that's not working, you also have to make sure the file is saved with encoding UTF-8. If you're using Notepad++, this is done via Encoding > Encode in UTF-8.
I have a simple error with my javascript file (Can't set property 'src' of null)
I am trying to change the image once in 1 second.
Here is my html code :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" src="function.js"></script>
</head>
<body >
<div class='bannerbg'>
<img src="img/2.jpg" alt="">
<div class='slider'></div>
</div>
</body>
</html>
Here is my JavaScript file:
images=new Array
(
"img/1.jpg",
"img/2.jpg",
"img/3.jpg"
);
function left() //this function change the index of the array of images
{
images.push(images.shift());
}
function change(){
i=document.querySelector("#bannerbg img");
i.src=images[0];
}
setInterval("left(); change()",1000);
Try this:
document.querySelector(".bannerbg img");
Your div has "bannerimg" as class, so you'll need to ude a period to tell the querySelector to look for a class.
The # is used to look for id properties, like this:
<div id='bannerbg'>
<img src="img/2.jpg" alt="">
<div class='slider'></div>
</div>
However, for maximum compatibility, I'd suggest adding a id to the image element:
<img src="img/2.jpg" alt="" id="myImage">
Then you can use document.getElementById("myImage") to access the specific element.
getElementById is one of the better supported DOM access functions, it will even work on IE versions as old as 5.5.
On a different note:
Your setInterval call is a bit of a bad practice. (See the explanation at the "code" parameter)
A better option would be to call it like this:
setInterval(function(){
left();
change();
},
1000);
Your selector comes up empty and thus the following attempt to set src fails.
In this line
<div class='bannerbg'>
you actually declare a class to that <div> and not an id. Within the selector, however, you use a #, which refers to ids. So either change the selector to use . as a class selector
i=document.querySelector(".bannerbg img");
or change your HTML to set an id instead of a class
<div id='bannerbg'>
Hey your using the id selector not a class selector # = id . = class. This means you dont select any element hence the error.
Try
document.querySelector(".bannerbg img");
I have no idea why this isn't working. I mean as far as I know It should print my array in alphabetical order to the div "output"
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> Lexicographic ordering </title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var words = [];
var input = prompt("Please enter a word or type end to stop prompts");
while (input != 'end') {
words.push(input);
input = prompt("Please enter a word or type end to stop prompts");
}
words.sort();
getElementById('#output').innerHTML= words.join();
</script>
</head>
<body>
<header>Lexicographic Ordering </header>
<hr>
<div class ="page-wrapper">
h1> Lexicographic Ordering </h1>
<div id="output"></div>
</div>
</body>
</html>
There are two small bugs in your code, and they're both in this line:
getElementById('#output').innerHTML= words.join();
getElementById is not a part of the window, it's a part of the document object, so you must reference it properly. Also, that method takes an ID, not a selector, so you don't need the # in front of it.
document.getElementById('output').innerHTML= words.join();
That should do what you want! Alternatively, since I notice you have jQuery included, you could do $('#output').innerHTML = ... to achieve the same effects.
You may also try to move the <script> block at the end, just before closing of the </body>. Anywhere after the <div id="output"></div>.
JavaScript on some browsers fails when they have to reference some elements which has not been parsed by their HTML parser when the script is executing or trying to reference them.
Also, you don't use # with getElementById(...);. # is used with Jquery. This is pure JavaScript. Make it getElementById('output').whatever...;
Edit:
Another option suggested by Patrick Evans is to move the JavaScript Code in an onload() event handler method to execute the code. This ensures that the HTML is fully loaded in the DOM before we try to manipulate it.
I am building an application which needs to select specific text between html, here is an example:
String:
<p>test1 test2test3</p>
RegExp: (Select text between HTML)(test.)
What I want to select is "test1","test2" and "test3" but not "test0"
Is there any solution??Thanks for any helps
Note: I am using JavaScript for RegExp operation.
You can leverage on the browser's ability to parse HTML for you:
var html = '<p>test1 test2test3</p>',
fragment = document.createDocumentFragment(),
div = fragment.appendChild(document.createElement('div'));
div.innerHTML = html;
console.log(div.textContent || div.innerText || '');
Outputs:
test1 test2test3
I wouldn't use Regexes for this kind of task, if all you need is text of <p> tag, I'd use
jQuery:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>test1 test2test3</p>
<script>
$(function(){
text = $('p').text();
alert(text);
});
</script>
</body>
</html>
This returns test1 test2test3
Working example: http://jsbin.com/uhadoz/1/
If you'd like a more generic solution, you still can use jquery, just change the selector:
for example, to get the text of all divs, use $('div').text()
But if you have serious parsing needs, you'd better use an HTML parser, google for
JavaScript HTML parser, for example this one: http://ejohn.org/blog/pure-javascript-html-parser/
Read this SO question about parsing HTML with Regexes: RegEx match open tags except XHTML self-contained tags