简体   繁体   English

在JavaScript中获取href和src属性的原始值

[英]Get the raw value of href and src attributes in javascript

Given an HTML element, I'd like to get the raw value of its src attribute using Javascript. 给定一个HTML元素,我想使用Javascript获取其src属性的原始值。

If the src value is relative path, element.src returns an absolute path. 如果src值为相对路径,则element.src返回绝对路径。

For example: 例如:

  1. //ssss.com ==> http(s)://ssss.com //ssss.com ==> http(s)://ssss.com

  2. blabla ==> http(s)://ssss.com/path/blabla blabla ==> http(s)://ssss.com/path/blabla

I know that it is possible to get the HTML code as string and to filter it, but this is not efficient. 我知道可以将HTML代码作为字符串进行过滤,但这并不是很有效。

I'm looking for efficient and clean way to extract the raw value of src/href attributes, given the HTML element with the attribute. 我正在寻找一种有效且干净的方法来提取src / href属性的原始值,给定具有HTML元素的属性。

Thanks! 谢谢!

Try with .getAttribute() 尝试使用.getAttribute()

 const src = document.getElementById("test").getAttribute("src") console.log(src) // logs "/source" 
 <img id="test" src="/source"/> 

You're confusing object properties with attribute values. 您正在将对象属性与属性值混淆。 What's wrong with just using getAttribute() ? 仅使用getAttribute()什么问题?

 var element = document.getElementById('test'); console.log( element.href ); console.log( element.getAttribute('href') ); 
 <a href="test.html" id="test">Testy</a> 

Notice that element.href is parsed by the browser, whereas getAttribute() returns the raw string that was specified in the DOM. 请注意, element.href由浏览器解析,而getAttribute()返回DOM中指定的原始字符串。 You can also similarly use getAttribute('src') for <img /> elements. 您也可以类似地对<img />元素使用getAttribute('src')

For completeness, this is the same behaviour that is demonstrated in jQuery. 为了完整起见,这与jQuery中演示的行为相同。 Most developers will use them synonymously, but they're actually subtly different. 大多数开发人员会以同义的方式使用它们,但实际上它们实际上有所不同。

For example: 例如:

 console.log( $('#test').prop('href') ); console.log( $('#test').attr('href') ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="test.html" id="test">Testy</a> 

Notice how prop() behaves in the same way as element.href , and attr() is identical to getAttribute() . 注意prop()行为方式与element.href相同,并且attr()getAttribute()相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM